0

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);  
0

1 Answer 1

1

Your regex strips any spaces, because that's what it looks for with (\s|^).

  1. Either use lookaround assertions (?<=\s|^) and (?=\s|$) there.

  2. Or assert non-wordy characters (?<!\w) and (?!\w) instead.

  3. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ty, it works! i use in $1 and $2 for get back spaces. ;D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.