如何在 PHP 中检查字符串中是否存在单词?

Patricia Arquette
发布: 2024-10-27 11:54:02
原创
748 人浏览过

How to Check If a Word Exists in a String in PHP?

如何使用 PHP 确定字符串中单词的存在

您正在寻找一个 PHP 函数来验证特定单词是否存在在一个更大的字符串中。考虑以下伪代码:

text = "I go to school"
word = "to"
if (word.exist(text)) {
    return true
else {
    return false
}
登录后复制

为了满足此要求,PHP 提供了多种满足不同场景的函数。

使用 strpos()

对于只需要确定单词是否存在的简单实例,strpos() 提供了一种简单的方法:

<code class="php">$needle = "to";  // The word you're searching for
$haystack = "I go to school";  // The string to be searched

if (strpos($haystack, $needle) !== false) {
    echo "Found!";
}</code>
登录后复制

使用 strstr()

如果您需要根据结果执行进一步的操作,strstr()提供了更大的灵活性:

<code class="php">if (strstr($haystack, $needle)) {
    echo "Found!";
}</code>
登录后复制

使用 preg_match()

对于涉及正则表达式的复杂模式,preg_match() 适合:

<code class="php">if (preg_match("/to/", $haystack)) {
    echo "Found!";
}</code>
登录后复制

定义自定义函数

来打包这些将功能转换为具有 Needle 和 haystack 默认值的自定义函数:

<code class="php">function match_my_string($needle = 'to', $haystack = 'I go to school') {
  if (strpos($haystack, $needle) !== false) return true;
  else return false;
}</code>
登录后复制

使用 str_contains()(PHP 8.0.0 及更高版本)

PHP 8.0.0引入了 str_contains():

<code class="php">if (str_contains($haystack, $needle)) {
    echo "Found";
}</code>
登录后复制

以上是如何在 PHP 中检查字符串中是否存在单词?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!