-1

I have string that I'm trying to manipulate, for example, "Hello World"

I want to be able to check if the string contains the word "World" and if it does, wrap it in a <span>, so the end result would be:

"Hello <span>World</span>"

What would be the cleanest way to do this?

deceze
  • 510,633
  • 85
  • 743
  • 889
user1702965
  • 379
  • 5
  • 16
  • 2
    http://regular-expressions.info, http://php.net/preg_replace, or even just http://php.net/str_replace – deceze May 30 '18 at 14:57
  • 1
    There are many threads already on this topic. Have you tried any of those solutions and had issues? – user3783243 May 30 '18 at 14:57
  • 1
    Possible duplicate of [How do I check if a string contains a specific word?](https://stackoverflow.com/questions/4366730/how-do-i-check-if-a-string-contains-a-specific-word) – user3783243 May 30 '18 at 14:58

1 Answers1

0

You can use str_replace

$str = str_replace("World", "<span>World</span>", "Hallo World!");

Or preg_replace for more complex searching

WhiteRabbit
  • 322
  • 3
  • 12
  • 1
    Note this would match `Worlds` as well and make it `Worlds`. Not sure what the expected behavior is in that scenario. – user3783243 May 30 '18 at 15:00
  • That is true. You could avoid that using preg_replace but if we dont know the use case we can just guess :-) – WhiteRabbit May 30 '18 at 15:06