2017-06-08 28 views
0

如何解决此问题:查找单词的文字,PHP

编写查找文本的字一个PHP程序。 后缀通过管道与文本分开。 例如:后缀| SOME_TEXT;

input: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."; 
} 
+0

你的代码$ find是一个数组,strpos期望一个字符串 – rtfm

+0

find是一个数组。你不能使用数组和echo。你可以使用print_r或var_dump。另一种方法是foreach循环。 –

+0

您应该搜索'$ find [1]',它包含管道后面的输入部分。 – Barmar

回答

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'."; 
} 
+0

谢谢,但是如何显示“查找”字样,echo“查找”字样? – user2708032

+0

'$ match [0]'包含这个单词。 – Barmar

+0

谢谢,我明白了; ) – user2708032