繁体   English   中英

如何在PHP中使用正则表达式从字符串中找到子字符串?

[英]How to find a substring from a string using regular expression in php?

我有一个类似“我爱我的国家”的字符串。 如果我搜索“国家”,我的程序将显示“存在”。 但是,如果我搜索“计数”,我的程序将显示“不存在”。

是您要找的东西吗?

我不是Regex的主人,所以有人可能会提供更理想的解决方案,但是仅搜索带有单词边界的国家应该可以为您提供帮助。

/\\b(country)\\b/g

因此,在PHP中,如下所示:

$string = 'I love my country';
$matchExists = preg_match('/\b(country)\b/', $string);

echo ($matchExists) ? 'Match Found' : 'No Match Found'; // Output: Match Found

失败的是:

$string = 'I love mycountry';
$matchExists = preg_match('/\b(country)\b/', $string);

echo ($matchExists) ? 'Match Found' : 'No Match Found'; // Output: No Match Found

提醒您,您可以在此处看到许多不同的输出,以及测试您可能拥有的任何其他输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM