php - 如何在字符串中查找字母并显示完整的单词
问题描述
如何用字母找到字符串中的单词?
示例(无代码):
String -> 你好,你住在 Oklahoma.city 很酷
查找 -> .city
显示 -> Oklahoma.city
我可以像这样检查是否存在:
$string = "Carlos.name its a name, Miami.city its a city, 15.number its a number";
if (stripos($string, '.city') !== false) {
echo "Exists";
}
但我需要展示Miami.city ..
非常感谢
解决方案
尝试使用正则表达式。这可以通过积极的前瞻来实现:
if (preg_match('[(?<city>\w+)(?=\.city)]', $string, $matches)) {
echo $matches['city'];
}
详细解释的表达式是这样的:
- 创建一个
city
匹配所有单词字符的命名组 (\w
) - 向前看,仅在找到字符串时匹配命名组
.city
推荐阅读
- graphene-django - 如何避免在 mutate() 函数中使用过多的参数?
- reactjs - .env 文件不显示自定义环境变量
- c# - Azure 认知服务 TTS - 示例应用中其他语言的错误
- python - 如何从元组列表中添加值
- .net - .net core Soap 服务器响应
- eclipse - 我的控制器不会收到用户的输入(Spring boot)
- reactjs - 如何在material-ui中使一张卡片的高度与其他卡片的高度相同?
- python - 用于 __bool__、__str__ 等的 Python lambda
- fonts - Font-Awesome 5 Icons 内容未显示
- react-native - 在 react-native 中,如何使 View 的背景颜色变为另一种颜色,然后淡出?