Remove character during preg_replace function
I need to extract some text from a string, th开发者_如何学编程en replace that text with a character removed in one instance and not in another. Hopefully this example will show you what I mean (this is what I have so far):
$commentEntry = "@Bob1990 I think you are wrong...";
$commentText = preg_replace("/(@[^\s]+)/", "<a target=\"_blank\" href=\"http://www.youtube.com/comment_search?username=${1}$1\">$1</a>", $commentEntry);
I want the result to be:
<a href="http://www.youtube.com/comment_search?username=Bob1990">@Bob1990</a> I think you are wrong...
But am getting:
<a href="http://www.youtube.com/comment_search?username=@Bob1990">@Bob1990</a> I think you are wrong...
I have been working on this one problem for at least an hour and nearly given up hope, so any help is greatly appreciated!
could try something like this
$commentText = preg_replace("/(@)([^\s]+)/", "<a target=\"_blank\" href=\"http://www.youtube.com/comment_search?username=$2\">$1$2</a>", $commentEntry);
What you can do is adapt the capturing. Move the @
out of the braces:
preg_replace("/@([^\s]+)/",
Then you can write your replacement string like
'<a href="...$1">@$1</a>'
Note how the first $1
just reinserts the text, and the second $1
is prefixed by a verbatim @
to get it back in.
You're capturing the @
in your pattern, so it'll always be output when you use $1
. Try this instead:
$commentText =
preg_replace(
"/@([^\s]+)/",
"<a target=\"_blank\" href=\"http://www.youtube.com/comment_search?username=$1\">@$1</a>",
$commentEntry
);
The difference here is that the @
is no longer captured as part of $1
(i.e. it'll capture only Bob1990. Since it's a literal value, it doesn't need to be part of any pattern. Instead, I just changed it to output as a literal value in the element text, directly before the captured name. (i.e. it now does <a>@$1</a>
rather than just <a>$1</a>
).
精彩评论