Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

php - Regular Expression match vs replace

In Php i wish to develop hashtag system with multi-language, For that i will use regular expression mechanism, for hash tag split and replace text with hyperlink.

First phase hash match will work for the given code

$str = '#????? ?????????? #??????';
preg_match_all('/#[^s#]*/i', $str, $mat);

$mat array has all hash tags in a input string like array([0]-#?????,[1] -#?????? )

Second phase replace hash tag with hyperlink given empty result for regular expression replace function like below

$str = '#?????,#??????';
$expression = "/#[^s#]*/i";        
$string = preg_replace($expression, '<a href="https://www.example.com/hash_tag?tag=$1">$0</a>', $str);

my expected result is #????? ?????????? #??????

how to fix this regular expression replace condition ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the pattern /#[^s#]*/i you don't need the /i because the negated character class matches any character except # or a whitespace char that includes upper and lower case characters.

In the replacement you use $0 and $1 which are the full match and capture group 1. But the pattern currently has no capture group.

If the full match should include the # and group 1 without it, you can change the pattern to #([^s#]+) and repeat the character class 1+ times to match at least a character after the #

You can omit using preg_match_all and use only preg_replace:

echo preg_replace(
    '/#([^s#]+)/',
    '<a href="https://www.example.com/hash_tag?tag=$1">$0</a>',
    '#????? ?????????? #??????'
);

Output

<a href="https://www.example.com/hash_tag?tag=?????">#?????</a> ?????????? <a href="https://www.example.com/hash_tag?tag=??????">#??????</a>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...