Using PHP replace regex with regex

后端 未结 3 1827
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 09:29

I want to replace hash tags in a string with the same hash tag, but after adding a link to it

Example:

$text = \"any word here related to #English mu         


        
3条回答
  •  暖寄归人
    2020-12-06 10:00

    If you need to refer to the whole match from the string replacement pattern all you need is a $0 placeholder, also called replacemenf backreference.

    So, you want to wrap a match with some text and your regex is #\w+, then use

    $text = "any word here related to #English must #be replaced.";
    $text = preg_replace("/#\w+/", "$0", $text);
    

    Note you may combine $0 with $1, etc. In case you need to enclose a part of the match with some fixed strings you will have to use capturing groups. Say, you want to get access to both #English and English within one preg_replace call. Then use

    preg_replace("/#(\w+)/", "$1", $text)
    

    Output will be any word here related to English must be replace.

提交回复
热议问题