【发布时间】: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