【问题标题】:Get specific string from string, starting with pattern从字符串中获取特定字符串,以模式开头
【发布时间】:2019-03-20 06:25:26
【问题描述】:

我收到这样的字符串:

class1 fa-dollar class2 class3

现在,我需要检查这个字符串是否有包含fa-* 的字符串/单词。我如何使用 PHP 来管理它?

逐字代码

if(custom_strpos($myReceivedString, 'fa-')) {
    echo $faStringOnly;
    // output: 'fa-dollar'
}

提前致谢。

【问题讨论】:

  • 分解、循环和子串。当有多个fa- 时,你需要做什么?
  • 支票是什么意思?如果您需要做的只是实际检查,那么strpos($string, "fa-") !== false 就足够了。
  • @DirkScholten 我不知道最后会出现什么fa-*。我知道我必须搜索模式fa-,但必须接收完整的字符串(如上例中的fa-dollar
  • @MonkeyZeus 循环是一个选项,创建一个函数并让它像这样,但应该有更简单的东西(比如正则表达式)?不过谢谢,至少我现在有一个解决方案。
  • preg_match/(fa-[^\s]*)/explodepreg_grep

标签: php string-matching


【解决方案1】:

让我们从两个代码示例开始:

$example = "class1 fa-dollar class2 class3";
if (preg_match_all('/(fa-\w+)/', $example, $matches)) {
  foreach ($matches[0] as $match) {
    print $match . "\n";
  }
}

$moreThan1 = "class1 fa-dollar class2 fa-other class3";
if (preg_match_all('/(fa-\w+)/', $example, $matches)) {
  foreach ($matches[0] as $match) {
    print $match . "\n";
  }
}

第一个例子就是你的例子。我们使用preg_match_all 匹配所有实例。在您的示例中,只有一个。正则表达式匹配是/fa-\w+/,它表示“此匹配以fa- 开头,然后有1 个或多个基于单词的字符。(我根据fa-dollar 做出这个假设,我假设它是来自Font Awesome 的类。

找到的匹配项被放入$matches,示例代码显示了如何循环访问它们。

为了证明这适用于多个匹配项,您可以查看第二个示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 2013-07-18
    相关资源
    最近更新 更多