如何使用PHP检查另一个字符串中是否包含一个单词? [英] How can I check if a word is contained in another string using PHP?

查看:92
本文介绍了如何使用PHP检查另一个字符串中是否包含一个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伪代码

text = "I go to school";
word = "to"
if ( word.exist(text) ) {
    return true ;
else {
    return false ;
}

我正在寻找一个PHP函数,如果文本中存在该单词,该函数将返回true.

I am looking for a PHP function which returns true if the word exists in the text.

推荐答案

您可以根据需要选择几种方法.对于这个简单的示例,strpos()可能是最简单,最直接的函数.如果需要对结果进行某些操作,则可以选择strstr()preg_match().如果您需要使用复杂的图案而不是字符串作为针,则需要preg_match().

You have a few options depending on your needs. For this simple example, strpos() is probably the simplest and most direct function to use. If you need to do something with the result, you may prefer strstr() or preg_match(). If you need to use a complex pattern instead of a string as your needle, you'll want preg_match().

$needle = "to";
$haystack = "I go to school";

strpos()和stripos()方法(stripos()不区分大小写):

strpos() and stripos() method (stripos() is case insensitive):

if (strpos($haystack, $needle) !== false) echo "Found!";

strstr()和stristr()方法(stristr不区分大小写):

strstr() and stristr() method (stristr is case insensitive):

if (strstr($haystack, $needle)) echo "Found!";

preg_match方法(正则表达式,更灵活但运行更慢):

preg_match method (regular expressions, much more flexible but runs slower):

if (preg_match("/to/", $haystack)) echo "Found!";

因为您要求一个完整的功能,所以这是将它们组合在一起的方式(带有needle和haystack的默认值):

Because you asked for a complete function, this is how you'd put that together (with default values for needle and haystack):

function match_my_string($needle = 'to', $haystack = 'I go to school') {
  if (strpos($haystack, $needle) !== false) return true;
  else return false;
}

这篇关于如何使用PHP检查另一个字符串中是否包含一个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆