Php 如何从字符串中删除精确匹配?

Php 如何从字符串中删除精确匹配?,php,Php,如何从字符串(示例字符串)中替换/删除完全匹配的单词 $string = 'Hello world, command data test com'; 如何删除com(与字符串完全匹配),但不将com从命令中删除到,您需要使用。基本上,preg_replace()搜索主题以查找模式匹配项,并用替换项替换它们 <?php $string = 'Hello world, command data test com'; $string = preg_replace('/\bcom\b

如何从字符串(示例字符串)中替换/删除完全匹配的单词

$string = 'Hello world, command data test com';
如何删除com(与字符串完全匹配),但不将com从命令中删除到,您需要使用。基本上,
preg_replace()
搜索主题以查找模式匹配项,并用替换项替换它们

<?php
   $string = 'Hello world, command data test com';
   $string = preg_replace('/\bcom\b/', '', $string);
   echo $string;
?>

解释:下面解释上述示例模式

\b:匹配单词边界
com:要匹配的文本

有关更多特殊字符定义,请检查短版本:

join(' ',array_diff(explode(' ', $string), ['com']));
说明:

  • explode(“”,$string)
    将字符串拆分为一个单词数组
  • array_diff($words,['com'])
    从第一个数组中删除第二个数组中的元素。因此,如果
    $words
    数组包含单词
    com
    ,它将被删除
  • 连接(“”,$words)
    连接
    $words
    数组中的所有字符串,用空格分隔每个单词
完整片段:

另一个版本。。。。
如果输入字符串始终按此顺序排列,则可以使用
rtrim

片段

$string = 'Hello world, command data test com';
$string = rtrim($string, ' com');
echo $string;
输出

Hello world, command data test
生活

文件

str\u replace正在将com从命令中删除到,这对您没有帮助!这就是我需要的@Smartpal我不这么认为,str_replace()replace命令mand@ShanteshwarInde是的,那是。。。。对不起,我忘了指挥部。向上的Voted@ShanteshwarInde完成后,我需要再等4分钟才能接受,尽管我的答案有更多的投票,但这是我最喜欢的!只需添加解释,让更多人理解。谢谢我真的觉得你的更好!哈哈,我会补充一些更好的解释