tiny_trevor
tiny_trevor

Reputation: 69

str_replace on string only if it INCLUDES a whitespace

I have a substitution code that replaces all instances of XD with an XD smiley face... thing is, should a link include the string 'XD', it then breaks the link.

I want it to only replace the XD, if it is followed by a whitespace, as in 'XD ', except I can't seem to get it to work (tried &nbsp, /\s/ and   as in 'XD&nbsp')

Chances are I'm getting something really obvious wrong, but I can't find any help (all of it seems to be about removing whitespace, not requiring it), so I'm hoping someone can help me.

Here's the code for reference:

 function BB_CODE($content) {
   $content = str_replace("XD", "<img src=\"images/smilies/icon_xd.gif\" alt=\"XD\">", $content);
}

The content is user input. Thanks for any help!

Upvotes: 1

Views: 83

Answers (2)

sba
sba

Reputation: 2117

So you want to replace XD only if it's alone?

preg_replace('/\bXD\b/', '(ಠ‿ಠ)', "Then I was like XD")

Use \b to watch for word boundaries instead of \s. This means it works at the beginning and the end of string too, like in my example.

With preg_replace() there are two common gotchas:

  • The separator char, I used / here by convention but in my own code I prefer %. You could write the regex as '%\bXD\b%' with the same meaning.
  • Escaping the backslashes, I used a single quoted string so I don't have to escape the backslash in \b. If you use double qoutes, you have to escape it, like so: "/\\bXD\\b/"

Upvotes: 0

Mohammed Doulfakar
Mohammed Doulfakar

Reputation: 128

You should surround "XD" with %

$content= str_replace("%XD%", "<img src=\"images/smilies/icon_xd.gif\" alt=\"XD\">", $content);

EDIT : Or using preg_replace

preg_replace("/XD/", "<img src=\"images/smilies/icon_xd.gif\" alt=\"XD\">", $content);

Upvotes: 1

Related Questions