PHP返回字符串开头的子字符串作为变量?

时间:2018-08-16 08:18:41

标签: php

例如:在

"Why is the sky blue?" 

我如何检测以下子字符串之一:

"What is", 
"Who is", 
"Why is", 
"How is", 
"Where is", 
"When is" 

包含在字符串的开头,然后如何将其作为变量返回。

1 个答案:

答案 0 :(得分:0)

我不确定在这里想要什么“然后如何将其作为变量返回” ,但是您可以检查此解决方案并提供更多信息:

<?php

$words = ['Who is', 'Why is', 'How is', 'Where is', 'When is'];

$query = 'Why is the sky blue?';

foreach ($words as $word) {
    if (substr($query, 0, strlen($word)) === $word) {
        $found = $word;
    }
}

因此,在此示例的最后,$found将包含“为什么” ,最好在使用isset(); $found;进行检查>