【问题标题】:PHP exclude conflictPHP排除冲突
【发布时间】:2021-03-03 18:45:24
【问题描述】:

我有一个问题: 我有一系列要排除的单词 (例:黄黄表) 我用 str_replace 这个词替换为同一个词,周围有标签以排除,但我有一个问题:

我认为问题出在表中出现冲突的单词时要排除的单词顺序,但是我无法提前手动对其进行排序,因为我不知道它们(这是用户填写它们)

我该怎么做?

这是我的代码:

$text = "I want to exclude the Yellow table in php";

$excluded_words_wrappers = array('<span>', '</span>');
$excluded_words = array('table', 'Yellow table');

foreach ($excluded_words as $excluded_word) {
    $excluded_word = trim($excluded_word);
    $match = "{$excluded_words_wrappers[0]}{$excluded_word}{$excluded_words_wrappers[1]}";
    $text = str_replace($excluded_word, $match, $text);
}

echo $text;

/**
 - Example sentence: I want to exclude the Yellow table in php  
 - What i get with my code: I want to exclude the <span>yellow</span> table in
   php
 - What I want: I want to exclude the <span>Yellow table</span> in
   php
**/

【问题讨论】:

    标签: php string replace str-replace


    【解决方案1】:

    按长度对排除的单词列表进行排序 (strlen($excluded_word)),这样较长的单词首先出现(索引 0),较短的单词出现在最后。

    因此,“黄色表格”出现在“黄色”之前。您不在乎“蓝色”是否不合适,只在乎它出现在与它发生冲突的任何事物之后。例如:

    • 表格
    • 黄色
    • 黄桌
    • 蓝色
    • 蓝色桌子

    将排序为:

    • 黄桌
    • 蓝色桌子
    • 黄色
    • 表格
    • 蓝色

    当一个排除的单词包含另一个排除的单词时,您的问题就会出现。任何包含另一个排除词的排除词,就其本质而言,必须比包含的排除词长。例如,如果您要在“yellow table”之前处理“yellow”并将“yellow”更改为“red”(或使用&lt;span&gt;&lt;/span&gt; 包装),那么所有出现的“yellow table”都将更改为“red table” .但是如果你先处理较长的排除词,那么你会在处理'yellow'之前处理'yellow table',你会得到你想要的结果。

    在您的 foreach 语句之前发出排序命令。您可以将 usort() 与用户定义的比较函数一起使用。 usort syntax

    【讨论】:

    • 谢谢,我确实没有想到。另一方面,通过使他最长的单词被span包围,但较短的单词也会被span包围,有没有办法避免这种情况?避免“排斥中的排斥”。避免这个:``` 黄色table```
    • 使用 preg_replace() 代替 str_replace() 使得排除的词不能以 >​​ 开头,也不能在 之后
    【解决方案2】:

    使用preg_replace:

    <?php
    // first arg is text to replace on, all remaining arguments are words you wrap in a span *(except last true or 1 - that makes it case sesitive)*
    function spanWords(...$args){
      $str = array_shift($args); $end = end($args);
      if($end === true || $end === 1){
        array_pop($args); $i = '/';
      }
      else{
        $i = '/i';
      }
      return preg_replace('/'.join('|', $args).$i, '<span>$0</span>', $str);
    }
    echo spanWords('I want to exclude the Yellow table in php', 'yellow table');
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 2011-08-21
      • 1970-01-01
      • 2011-04-17
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多