首页 > 解决方案 > 如何在字符串中查找字母并显示完整的单词

问题描述

如何用字母找到字符串中的单词?

示例(无代码):

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 ..

非常感谢

标签: php

解决方案


尝试使用正则表达式。这可以通过积极的前瞻来实现:

if (preg_match('[(?<city>\w+)(?=\.city)]', $string, $matches)) {
    echo $matches['city'];
}

详细解释的表达式是这样的:

  1. 创建一个city匹配所有单词字符的命名组 ( \w)
  2. 向前看,仅在找到字符串时匹配命名组.city

推荐阅读