PHP 提取字符串中出现的每个项目


PHP Extract each occurrence of an item within a string

如果字符串显示:

从前,一个年轻的小LKT狼吞虎咽LKT发生了不幸的事故,LKTfellLKT。

我如何将LKT中包含的每个内容提取到数组中并在字符串中替换它们。

您可以尝试以下解决方案:

  • 将句子存储在变量中
  • explode()以空格为分隔符的句子
  • 遍历数组
  • 使用strpos()检查单词是否包含您的字符串
  • 如果是,请将单词推送到结果数组中

像这样:

$string = '...';
$words = explode(' ', $string);
foreach ($words as $word) {
    if (strpos($word, 'LKT') !== FALSE) {
        $result[] = $word;
    }
}
print_r($result);

输出:

Array
(
    [0] => LKTgoblingLKT
    [1] => LKTfellLKT.
)

演示!


如果要将字符串替换为另一个单词,可以使用 str_replace()implode() ,如下所示:

$string = '...';
$words = explode(' ', $string);
$result = array();
foreach ($words as $word) {
    if (strpos($word, 'LKT') !== FALSE) {
        $word = str_replace($word, 'FOO', $word);
    }
        $result[] = $word;
}
$resultString = implode(' ', $result);
echo $resultString;

输出:

Once upon a time a small young FOO had an unfortunate accident and FOO

演示!