假设我有一个这样的字符串
我今年7月从底特律飞往温哥华
$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"
我在想也许可以在str_replace
前加一个空格来炸掉$string
,这样我就可以
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
过程中完全忽略它们。
当然,我并不反对使用preg_replace这样的str_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"
)中,因此应该跳过这个单词,因为它在引号中。
发布于 2018-06-04 08:21:05
使用正则表达式会更容易,使用PHP (PCRE)会更容易。使用PCRE,您可以使用(*SKIP)
回溯动词进行匹配和跳过。你匹配一个双引号的字符串,然后让引擎从整体匹配中跳过这一部分,并在交替的第二侧键入你想要的模式。
"[^"\\]*(?:\\.[^"\\]*)*"(*SKIP)(*F)
上面的正则表达式匹配双引号字符串(包括转义的双引号),然后告诉引擎忘记。
这将是实现此功能的PHP代码,以及在正则表达式中收集停用词:
echo preg_replace('/"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"(*SKIP)(*F)|\b(?:'
. implode('|', array_map('preg_quote', $stopwords))
. ')\b\h*/', '', $string);
发布于 2018-06-04 08:09:41
foreach ($stopwords as &$stopword) {
$string = str_replace($stopword, ' ', $string);
}
https://stackoverflow.com/questions/50671864
复制相似问题