如何在PHP中返回包含特定单词的句子

时间:2018-12-02 22:40:48

标签: php

就像标题中一样,我想知道只有在其中包含特定单词的情况下,我才能轻松地返回句子吗?

让我说我有一个数组:

$strings = array("Hello World", "Hello Earth", "Hi World");
$match = "Hello";
foreach ($strings as $string) {
  echo $string;
  //And here i want to return only strings with "Hello",
  //In this case it should only return:
  //Hello World,
  //Hello Earth
}

有人可以帮忙吗? :)

1 个答案:

答案 0 :(得分:2)

使用strpos()检查字符串是否包含所选单词。

$strings = array("Hello World", "Hello Earth", "Hi World");
$match = "Hello";
foreach ($strings as $string) {
  if (strpos($string, $match) !== false) {
      echo $string;
  }
}