如何在php中使用preg_replace()替换给定字符串?

如何在php中使用preg_replace()替换给定字符串?,php,Php,我试图用以下代码替换字符串 $find2 = array ('/is/', '/working/'); $replace2 = array ('to', 'work'); $data="During the day, Damien is working"; echo preg_replace ($find2, $replace2, $data); 输出为 白天,达米恩去上班 但我希望结果是 达米恩去上班了 您应该将“白天”替换为“”。要在白天删除,Damien正在工作您可以使用以下选

我试图用以下代码替换字符串

$find2 = array ('/is/', '/working/'); 
 $replace2 = array ('to', 'work');
 $data="During the day, Damien is working";
 echo  preg_replace ($find2, $replace2, $data);
输出为

白天,达米恩去上班

但我希望结果是

达米恩去上班了


您应该将“白天”替换为“”。

要在白天删除
,Damien正在工作
您可以使用以下选项:

$data = str_ireplace('During the day, Damien is working', 'Damien to work', $data);
以便:

$data = "During the day, Damien is working";
$data = str_ireplace('During the day, Damien is working', 'Damien to work', $data);
echo $data;
将回显(输出):

根据您的要求。

代码:

$data="During the day, Damien is working";
echo preg_replace("/.*,(.*)/i","$1",$data);
$find2 = array ('/is/', '/working/',"/.*,(.*)/"); 
 $replace2 = array ('to', 'work',"$1");
 $data="During the day, Damien is working";
 echo  preg_replace ($find2, $replace2, $data);
输出:

$data="During the day, Damien is working";
echo preg_replace("/.*,(.*)/i","$1",$data);
$find2 = array ('/is/', '/working/',"/.*,(.*)/"); 
 $replace2 = array ('to', 'work',"$1");
 $data="During the day, Damien is working";
 echo  preg_replace ($find2, $replace2, $data);
达米恩在工作

会有用的。它将删除“Anything,String”到“String”。删除“、”之前的所有内容


对于您的代码,您希望数据数组替换这两件事+据我所知,您也希望替换它。 所以

代码:

$data="During the day, Damien is working";
echo preg_replace("/.*,(.*)/i","$1",$data);
$find2 = array ('/is/', '/working/',"/.*,(.*)/"); 
 $replace2 = array ('to', 'work',"$1");
 $data="During the day, Damien is working";
 echo  preg_replace ($find2, $replace2, $data);
输出:

$data="During the day, Damien is working";
echo preg_replace("/.*,(.*)/i","$1",$data);
$find2 = array ('/is/', '/working/',"/.*,(.*)/"); 
 $replace2 = array ('to', 'work',"$1");
 $data="During the day, Damien is working";
 echo  preg_replace ($find2, $replace2, $data);
达米恩去上班了


此代码不会执行任何会在白天删除
“的操作”
。您到底尝试了什么来完成这一部分?除了删除字符串之外,还有其他删除字符串的方法吗?是否有其他方法可以将此“在白天”替换为“”。您可以使用str_replace函数。根据你的要求,它比preg_replace要好。为什么只有正则表达式?@ngen:他根本没有解释他的真正问题。我感觉他在做一些不知道如何编码的家庭作业。@Brunothileban,正则表达式比一个简单的
str\u ireplace()
函数要昂贵得多。我不会建议你用更丑陋的方式来做我上面解释的事情。@Jeffrey如果名字改成“Jeffrey”而不是“Damien”,你会怎么做?。请你重写代码好吗?对不起,这是我面试时的一个问题。这就是我问的原因。@ngen,没什么更简单的:
$name=“Damien”$data=str_ireplace(“白天,$name在工作,$name在工作,$data”)。Regex根本不是这里的解决方案。如果“工作”变为“运行”?。你能继续写stru_replace吗?很好。我们可以用“Damien正在工作”代替“Damien正在工作”吗?正则表达式在这里是一种过分的表达方式。