繁体   English   中英

在带有特殊字符的字符串中查找子字符串PHP

[英]Find a substring inside a string with special characters PHP

我有一个像这样的复杂字符串

{},\"employees\":{},\"idIwant\":{\"2545\":{\"attributes\":{\"offset\":9855,

我需要从此字符串中提取出甜美的2545 ,我尝试使用正则表达式和strpos,但在很多冒号,方括号和斜杠的情况下效果不佳。 是否可以在idIwant之后提取数字,即2545

这实际上来自网站的源代码,它不是json,而是redux状态字符串。

像这样隔离比赛后的数字:

代码:( 演示

$string = '{},\"employees\":{},\"idIwant\":{\"2545\":{\"attributes\":{\"offset\":9855,';

echo preg_match('~"idIwant\\\":{\\\"\K\d+~', $string, $out) ? $out[0] : 'bonk';

输出:

2545

保持搜索关键字周围的"\\"非常重要,这样您才能匹配整个目标关键字(无意间导致子字符串不匹配)。

\\K重新启动全字符串匹配,因此您不需要使用不必要的元素来膨胀输出数组。

Php要求3或4 \\表示模式中的1。 (这里有一些故障: https : //stackoverflow.com/a/15369828/2943403

ps或者,您可以强制使用\\Q..\\E来完全解释模式的开头部分,如下所示:

演示版

echo preg_match('~\Q\"idIwant\":{\"\E\K\d+~', $string, $out) ? $out[0] : 'bonk';

或者,如果您害怕这么多元字符,可以降低模式的稳定性,只匹配搜索字符串,然后匹配一个或多个非数字,然后忘记先前匹配的字符,然后匹配1个或多个数字:

echo preg_match('~idIwant\D+\K\d+~', $string, $out) ? $out[0] : 'bonk';

如果idIwant只有数字,这将起作用。

$string = '{},\"employees\":{},\"idIwant\":{\"2545\":{\"attributes\":{\"offset\":9855,';

preg_match('/idIwant.*?(\d+)/', $string, $matches);

echo $matches[1];

测试

最简单的方法是:

$String ='{},\"employees\":{},\"idIwant\":{\"2545\":{\"attributes\":{\"offset\":9855,';

$arr1 = explode('"idIwant\":{\"', $String);

如果输出$arr1[1] ,将得到:

string=> 2545\":{\"attributes\":{\"offset\":9855,';

你需要:

$arr2 = explode('\":{\"', $arr1[1]);

你会得到$arr2[0]

string=> 2545

如果字符串具有严格的语法

获得所需数字的方法有很多,其中一种是类似于以下内容的表达式:

.+idIwant\\":{\\"(.+?)\\.+

演示版

测试

$re = '/.+idIwant\\\\":{\\\\"(.+?)\\\\.+/m';
$str = '{},\\"employees\\":{},\\"idIwant\\":{\\"2545\\":{\\"attributes\\":{\\"offset\\":9855,';
$subst = '$1';

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;

暂无
暂无

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

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