使用 str_replace 匹配整个单词/不区分大小写
using str_replace to match whole words /case insensitive
我正在尝试使用 str_replace 替换字符串中的整个单词,但是,即使单词中匹配的字母也会被替换。我尝试了 preg_replace,但无法正常工作,因为我有一大堆要替换的单词。任何帮助表示赞赏。
$array2 = array('is','of','to','page');
$text = "homepage-of-iso-image";
echo $text1 = str_replace($array2,"",$text);
the output is : home--o-image
对于全词问题,有 a solution here using preg_replace(), and your the solution would be to add /\b
to the beginning and \b/u
to the end of your array-values. The case-insensitive could be handled with preg_replace_callback (参见示例 #1),但如果您使用的是像示例这样的小数组,我只建议复制数组值。
应用于您的示例:
$array2 = array(
'/\bis\b/u',
'/\bof\b/u',
'/\bto\b/u',
'/\bpage\b/u',
'/\bIS\b/u',
'/\bOF\b/u',
'/\bTO\b/u',
'/\bPAGE\b/u'
);
$text = "homepage-of-iso-image";
echo $text1 = preg_replace($array2,"",$text);
你可以使用 array_diff
array array_diff ( array $array1 , array $array2 [, array $... ] )
Compares array1 against one or more other arrays and returns the
values in array1 that are not present in any of the other arrays.
<?php
$remove = array('is','of','to','page');
$text = "homepage-of-iso-image";
$parts = explode('-', $text);
$filtered = array_diff($parts, $remove);
print implode('-', $filtered);
输出:
homepage-iso-image
我正在尝试使用 str_replace 替换字符串中的整个单词,但是,即使单词中匹配的字母也会被替换。我尝试了 preg_replace,但无法正常工作,因为我有一大堆要替换的单词。任何帮助表示赞赏。
$array2 = array('is','of','to','page');
$text = "homepage-of-iso-image";
echo $text1 = str_replace($array2,"",$text);
the output is : home--o-image
对于全词问题,有 a solution here using preg_replace(), and your the solution would be to add /\b
to the beginning and \b/u
to the end of your array-values. The case-insensitive could be handled with preg_replace_callback (参见示例 #1),但如果您使用的是像示例这样的小数组,我只建议复制数组值。
应用于您的示例:
$array2 = array(
'/\bis\b/u',
'/\bof\b/u',
'/\bto\b/u',
'/\bpage\b/u',
'/\bIS\b/u',
'/\bOF\b/u',
'/\bTO\b/u',
'/\bPAGE\b/u'
);
$text = "homepage-of-iso-image";
echo $text1 = preg_replace($array2,"",$text);
你可以使用 array_diff
array array_diff ( array $array1 , array $array2 [, array $... ] )
Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.
<?php
$remove = array('is','of','to','page');
$text = "homepage-of-iso-image";
$parts = explode('-', $text);
$filtered = array_diff($parts, $remove);
print implode('-', $filtered);
输出:
homepage-iso-image