开发者

Modifying back reference on regular expression (PHP)

开发者 https://www.devze.com 2023-01-17 20:43 出处:网络
Getting frustrated... So, I want to modify the back reference of a preg_replace. Figured I can\'t actually modify (?) so am wondering if it\'s possible to change the regex to achieve same result.

Getting frustrated...

So, I want to modify the back reference of a preg_replace. Figured I can't actually modify (?) so am wondering if it's possible to change the regex to achieve same result.

Example. Match [xx_xx] and output "xx_xx" and "xx xx". Th开发者_如何学运维e "xx_xx" is straightforward (as follows) but the "xx xx" ?

$y = "this [fishing_rod] is bent";
echo preg_replace("/\[(.+?)\]/", "\"\\1\", $y);
// this fishing_rod is bent

How do I achieve : this fishing_rod fishing rod is bent ?

(this is just an example, what I'm doing it is more complex !)


You need to use preg_replace_callback function

function fun($matches) {
        return str_replace('_',' ',$matches[1]); 
}

$y = "this [fishing_rod] is bent";
echo preg_replace_callback("/\[(.+?)\]/","fun", $y);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号