PHP 在匹配文本之前提取数字

问题描述 投票:0回答:3

所以我有点卡住了,我有一个这样的字符串:

$match = '**Mazon**'

$string = 'There are stores attached: Store1 (Detached) **28876.Mazon** (Detached) 28455.Targo (Detached) 28389.Walmo (Detached)'

输出:28876

这给了我28876,但是当我用 match =“Walmo”替换它时,它完全改变了。

需要先匹配Mazon,然后提取句点之前的数字。

到目前为止我得到的代码哈哈,我对 PHP 不太了解,但我正在尝试......

$data = strstr($string,".Mazon",true);
  
$output = substr($data, strpos($data, ")") +1);    

echo "<h1>" .$output ."</h1>";
php regex strpos
3个回答
4
投票

要匹配所有 3 个单词之前的数字,后跟一个点:

\b(\d+)\.(?:Mazon|Targo|Walmo)\b

解释

  • \b
    单词边界,防止成为较长单词的一部分
  • (\d+)
    捕获组 1,匹配或更多数字
  • \.(?:Mazon|Targo|Walmo)
    匹配
    .
    和替代方案之一
  • \b
    单词边界

查看 regex 演示php 演示

或者更宽一点的变体来匹配点后的大写字符

\b(\d+)\.[A-Z]

正则表达式演示

获取捕获组 1 的值的示例代码:

$re = '/\b(\d+)\.[A-Z]/';
$str = 'There are stores attached: Store1 (Detached) **28876.Mazon** (Detached) 28455.Targo (Detached) 28389.Walmo (Detached)';

preg_match_all($re, $str, $matches);
print_r($matches[1]);

输出

Array
(
    [0] => 28876
    [1] => 28455
    [2] => 28389
)

1
投票

您可以使用正则表达式来实现这一点。看这两个例子:

提取 Mazon 的值:

$str = 'There are stores attached: Store1 (Detached) **28876.Mazon** (Detached) 28455.Targo (Detached) 28389.Walmo (Detached)';

$regexMazon = '/([0-9]*?)\.Mazon/';
preg_match($regexMazon, $str, $matches);

// Check if matches are found, the group is stored in $matches[1]
if (count($matches) > 1) {
    var_dump($matches[1]);  
}

输出将是:

string(5) "28876"

如果你想获取 Targo 的值,你可以在正则表达式中替换 Mazon:

$regexTargo = '/([0-9]*?)\.Targo/';
preg_match($regexTargo, $str, $matches);

// Check if matches are found, the group is stored in $matches[1]
if (count($matches) > 1) {
    var_dump($matches[1]);  
}

输出:

string(5) "28455"


0
投票

在正则表达式中,匹配一个或多个数字,然后使用前瞻来匹配后跟输入单词的文字点。 代码片段中使用

preg_quote()
来转义对正则表达式引擎具有特殊含义的任何字符 - 对于问题中提供的示例字符串在技术上来说是不必要的。 演示

$haystack = 'There are stores attached: Store1 (Detached) **28876.Mazon** (Detached) 28455.Targo (Detached) 28389.Walmo (Detached)';

foreach (['Mazon', 'Targo', 'Walmo', 'Foo'] as $needle) {
    printf(
        "%s => %s\n",
        $needle,
        preg_match('#\d+(?=\.' . preg_quote($needle) . ')#', $haystack, $m) ? $m[0] : 'no match'
    );
}

输出:

Mazon => 28876
Targo => 28455
Walmo => 28389
Foo => no match
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.