在PHP中,我试图用substr
函数删除特定单词。
我这样做的方式是:
检查字符串中是否确实存在该字:
$haystack = "/home/{i:id}/{s:aString}";
$needle = "{i:id}";
if ($position = strpos($haystack, $needle)) {...}
使用substr
$haystack = "/home/{i:id}/{s:aString}";
$needle = "{i:id}";
if ($position = strpos($haystack, $needle)) {
$rpos = strpos($haystack, substr($needle, -1), $position);
...
}
再次使用substr
打印单词
$haystack = "/home/{i:id}/{s:aString}";
$needle = "{i:id}";
if ($position = strpos($haystack, $needle)) {
$rpos = strpos($haystack, substr($needle, -1), $position);
echo substr($haystack, $position, $rpos);
}
当运行这段代码时,它会删除整个单词,但会停止延迟,它还会占用字符串剩余部分的5个字符。
如何解决这个问题,所以只会找到我想要的字?
答案 0 :(得分:0)
我没有足够的声誉所以发布回答。试试这个,
<?php
$sentence = "I want to remove all the common words from this sentence because they are irrelevant";
$common_words = array("to ", "this ", "all ", "the ", "from ");
$newphrase = str_replace($common_words, "", $sentence);
echo "Actual Word : ".$sentence."\n\nNew Word : ".$newphrase;
?>
如果有帮助,请告诉我。