dongtiao5094 2014-01-22 16:46
浏览 27
已采纳

PHP preg_replace - 在结果中包含模式/完整主题

I've a problem that I couldn't solve myself: replace...

locale("Sendx", "Send")
locale("System", "System")

should become:

locale("Sendx", "Subsub")
locale("System", "Newsys")

I tried a simple replace:

$mysearchword = "System"; #changes in a loop
$myreplaceword = "Newsys"; #also changes in the loop
$oneline = str_replace($mysearchword, $myreplaceword, $oneline);

but the result looks like

locale("Sendx", "53ND")
locale("Newsys", "Newsys") #problem with the doubled word

of course the System was replaced both times. So I decided to use preg_replace

$pattern = '/locale\\(["|\']([^"\']*)["|\'], ["|\']([^"\']*)["|\']\\)/';
$replacement = '${1}, Newsys';
$subject = 'locale("System", "System")';
echo preg_replace($pattern, $replacement, $subject, -1 );

But now nearly anything is missing, because only the words in the brackets are returned and I have no idea how to include the pattern or return a replaced $subject. The $pattern changes, so I couldn't write "locale(..." into the $replacement / I somehow must return a replaced pattern...

System, Newsys # No idea how to combine $replacement with $pattern...

Could you please help me to get the right result?

  • 写回答

4条回答 默认 最新

  • dongyan1899 2014-01-22 16:54
    关注

    I guess you are looking for something like this:

    $input  = 'locale("Sendx", "Send")';
    $output = preg_replace('/, "(.*?)"/', ', "Subsub"', $input);
    echo $output;
    echo "
    ";
    
    $input  = 'locale("System", "System")';
    $output = preg_replace('/, "(.*?)"/', ', "Newsys"', $input);
    echo $output;
    

    Output:

    locale("Sendx", "Subsub")
    locale("System", "Newsys")
    

    The pattern /, "(.*?)"/ searches for the word between double quotes " after the comma and replaces it with , "NEW_WORD"

    Using this pattern, you can easily replace them in a loop:

    $input = array(
      'locale("Sendx", "Send")' => 'Subsub',  
      'locale("System", "System")' => 'Newsys'
    );
    
    foreach($input as $string => $replacement) {
        $output = preg_replace('/, "(.*?)"/', ', "' . $replacement . '"', $string);
        echo $output. PHP_EOL;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制