在文本中查找单词,php

时间:2017-06-08 22:44:12

标签: php

如何解决此问题:

编写一个PHP程序,在文本中找到单词。 后缀通过管道与文本分开。 例如:后缀| SOME_TEXT ;

输入:text | lorem ips llfaa Loremipsumtext。 输出:Loremipsumtext

我的代码就是这样,但逻辑可能是错误的:

$mystring = fgets(STDIN);
$find   = explode('|', $mystring);
$pos = strpos($find, $mystring);

if ($pos === false) {
    echo "The string '$find' was not found in the string '$mystring'.";
}
else {
    echo "The string '$find' was found in the string '$mystring',";
    echo " and exists at position $pos.";
}

1 个答案:

答案 0 :(得分:1)

explode()会返回一个数组,因此您需要使用$find[0]作为后缀,并使用$find[1]作为文本。所以它应该是:

$suffix = $find[0];
$text = $find[1];
$pos = strpos($text, $suffix);

if ($pos === false) {
    echo "The string '$suffix' was not found in '$text'.";
} else {
    echo "The string '$suffix' was found in '$text', ";
    echo " and exists at position $pos.";
}

但是,这会返回后缀的位置,而不是包含它的单词。它也没有检查后缀是否在单词的末尾,它会在单词的任何地方找到它。如果你想匹配单词而不仅仅是字符串,那么正则表达式将是一种更好的方法。

$suffix = $find[0];
$regexp = '/\b[a-z]*' . $suffix . '\b/i';
$text = $find[1];
$found = preg_match($regexp, $text, $match);

if ($found) {
    echo echo "The suffix '$suffix' was found in '$text', ";
    echo " and exists in the word '$match[0]'.";
} else {
    echo "The suffix '$suffix' was not found in '$text'.";
}