假设我有一个这样的字符串
我今年七月从“底特律飞往温哥华”
$string = 'I am flying from "Detroit to Vancouver" this July';
我还有一个“ stopwords
”数组(我选择从字符串/字符串中删除的单词)
$stopwords = array( "to", "anotherstopword", "andanother" )
现在我只是在使用
$string = str_replace($stopwords, ' ', $string);
这当然给了我 string(33) "I am flying from "Detroit Vancouver" this July"
我在想也许在$string
之前用一个空格爆炸str_replace
,给我类似的东西
Array
(
[0] => I
[1] => am
[2] => flying
[3] => from
[4] => "Detroit
[5] => to
[6] => Vancouver"
[7] => this
[8] => July
)
然后也许从数组中删除它们,进行替换,然后重新插入它们......但这似乎有点矫枉过正
我也考虑过使用这样的函数
function getStringBetween($str, $from, $to, $withFromAndTo = false)
{
$sub = substr($str, strpos($str, $from) + strlen($from), strlen($str));
if ($withFromAndTo)
return $from . substr($sub, 0, strrpos($sub, $to)) . $to;
else
return substr($sub, 0, strrpos($sub, $to));
}
这样做时,
echo '<pre>';
print_r(getStringBetween($string, '"', '"'));
echo '</pre>';
输出:
底特律到温哥华
并在 str_replace 之前做某种类型的忽略条件..
但是只要字符串中有多个引号,就会失败。
理想情况下,如果字符串包含双引号,我想创建一个条件,以在此str_replace
过程中完全忽略它们。
我当然不反对使用 str_replace 以外的其他东西,比如 preg_replace,但我没有足够的经验来为我的预期输出生成样本。
任何人都可以想出一种在替换之前忽略要删除的停用词/单词的好方法吗?
编辑:
代码示例
<?php
$stopwordstest = array( " to ", " a ", " test " );
$string = 'I am flying from "Detroit to Vancouver" this July when the weather is test nice';
var_dump($string);
// as is, without string replace
// string(79) "I am flying from "Detroit to Vancouver" this July when the weather is test nice"
$string = str_replace($stopwordstest, ' ', $string);
echo '<br><br>';
var_dump($string);
// string(71) "I am flying from "Detroit Vancouver" this July when the weather is nice"
// Expected output is:
//
// string(74) "I am flying from "Detroit to Vancouver" this July when the weather is nice"
//
?>
换句话说,我希望字符串替换按预期进行,但由于单词to
被封装在引号 ( "Detroit to Vancouver"
) 中,因此应该跳过该单词,因为它是在引号中。
使用正则表达式会很容易,使用 PHP (PCRE) 会更容易。使用 PCRE,您可以使用(*SKIP)
回溯动词进行匹配和跳过。您匹配一个双引号字符串,然后让引擎从整体匹配中跳过这部分,并在交替的第二侧输入您想要的模式。
"[^"\\]*(?:\\.[^"\\]*)*"(*SKIP)(*F)
上面的正则表达式匹配一个双引号字符串(包括转义的双引号),然后告诉引擎忘记。
这将是实现此功能以及在正则表达式中收集停用词的 PHP 代码:
echo preg_replace('/"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"(*SKIP)(*F)|\b(?:'
. implode('|', array_map('preg_quote', $stopwords))
. ')\b\h*/', '', $string);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句