Reputation: 69
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  , /\s/ and  
as in 'XD ')
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
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:
/
here by convention but in my own code I prefer %
. You could write the regex as '%\bXD\b%'
with the same meaning.\b
. If you use double qoutes, you have to escape it, like so: "/\\bXD\\b/"
Upvotes: 0
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