如何只在字符串中查找完整的单词 [英] How to find full words only in string

查看:184
本文介绍了如何只在字符串中查找完整的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅在字符串中查找完整的单词

How to find full words only in string

<?php
$str ="By ILI LIKUALAYANA MOKHTAKUALAR AND G. SURACH Datuk Dr Hasan Ali says he has no intention of joining Umno. Pic by Afendi Mohamed KUALA LUMPUR: FORMER Selangor Pas commissioner Datuk Dr Hasan Ali has not ruled out the possibility of returning to Pas' fold";
$search ="KUALA";
?>

推荐答案

要查看字符串中是否包含特定单词,可以使用带有单词边界的正则表达式,如下所示:

To see if a particular word is in a string, you can use a regular expression with word boundaries, like so:

$str = "By ILI LIKUALAYANA MOKHTAKUALAR AND G. SURACH Datuk Dr Hasan Ali says he has no intention of joining Umno. Pic by Afendi Mohamed KUALA LUMPUR: FORMER Selangor Pas commissioner Datuk Dr Hasan Ali has not ruled out the possibility of returning to Pas' fold";
$search = "KUALA";

if (preg_match("/\b$search\b/", $str)) {
    // word found
}

此处\b表示单词边界".它实际上不匹配任何字符,仅匹配边界,因此它匹配单词和空格之间的边缘,还匹配字符串末尾的边缘.

Here \b means "boundary of a word". It doesn't actually match any characters, just boundaries, so it matches the edge between words and spaces, and also matches the edges at the ends of the strings.

如果需要使其不区分大小写,可以将i添加到匹配字符串的末尾,如下所示:"/\b$search\b/i".

If you need to make it case-insensitive, you can add i to the end of the match string like this: "/\b$search\b/i".

如果您需要知道结果在字符串中的何处,则可以添加第三个$matches参数,该参数提供有关匹配的详细信息,如下所示:

If you need to know where in the string the result was, you can add a third $matches parameter which gives details about the match, like this:

if (preg_match("/\b$search\b/", $str, $matches)) {
    // word found
    $position = $matches[1];
}

这篇关于如何只在字符串中查找完整的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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