Reputation: 220
I try to build a Tagging System and it works fine there is an issue with function preg_replace(), it removes unnecessary spaces from the string.
An example of that is if my string is that
Hey !
@Yosi
@Ben
Spaces will be removed and it will become to that:
Hey!
@Yosi@Ben
It seems because my condition in preg_replace included as a string.
My code:
$String = preg_replace ('/(\s|^)@'.$Memory['Name'][$x].'(\s|$)/', '[URL="http://'.$_SERVER['HTTP_HOST'].'/member.php?u='.$Memory['UserID'][$x].'"]@'.$Memory['Name'][$x].'[/URL]', $String);
Upvotes: 0
Views: 125
Reputation: 145512
Your regex strips any spaces, because that's what it looks for with (\s|^)
.
Either use lookaround assertions (?<=\s|^)
and (?=\s|$)
there.
Or assert non-wordy characters (?<!\w)
and (?!\w)
instead.
Or even just reinsert them into your substitution text with $1
and $2
.
Also, your preg_replace looks like it is used in a loop. It's much simpler to just check all potential usernames by using preg_replace_callback
like:
$string = preg_replace_callback("/(?<!\w)@(\w+)(?!\w)/",
function($m) use ($names) {
list($asis, $name) = $m;
if ($isset($names[$name])) {
return "[URL=....]";
}
else return $asis;
},
$string
);
Style advise: And avoid uppercase variable names. PHP isn't BASIC.
Upvotes: 1