undefinedfix
Sign in

How to replace matched text with PHP regular matching

SeparateReality edited in Wed, 07 Sep 2022

such as

$content = "what's your favorite weapon, the double cut weapon, the cudgel is soft and the weapon is hard

I want to replace "weapon" with "weapon 123"

What function should be used to add the specified character after the matched regular

2 Replies
ferthalangur
commented on Wed, 07 Sep 2022

Regular implementation of the insert, with the packet capture replacement or zero width assertion can be

I don't understand PHP, but the following code runs in PHP online tools as expected

$content = "什么兵器最喜欢 双截兵器棍柔中兵器带刚\n";
echo preg_replace('/兵器/','${0}333',$content);
echo preg_replace('/(?<=兵器)/','333',$content);
dinara_pulseway
commented on Wed, 07 Sep 2022

$content ='What's your favorite weapon, double cut weapon, soft stick, hard weapon '; method 1: echo str_ Replace ("weapon", "weapon 333", $content); method 2: echo preg_ Replace ('/ weapon /', weapon 333 ', $content));