简体   繁体   English

PHP:从带有 preg_match、有限字符的字符串中获取值

[英]PHP: Get value from string with preg_match, limited characters

Sorry for the title, I don't know how to explain it better.对不起标题,我不知道如何更好地解释它。

I must get 354607 from the following string:我必须从以下字符串中获取354607

...jLHoiAAD1037 354607 Ij0Ij1Ij2... ...jLHoiAAD1037 354607 Ij0Ij1Ij2...

The "354607" is dynamic, but it has the "1037" in any case before, and is in any case exactly 6 characters long. “354607”是动态的,但在任何情况下它之前都有“1037”,并且在任何情况下都是 6 个字符长。

The problem is, the string is about 50.000 up to 1.000.000 characters long.问题是,字符串大约有 50.000 到 1.000.000 个字符长。 So I want a resource-friendly solution.所以我想要一个资源友好的解决方案。

I tried it with:我试过:

preg_match_all("/1037(.*?){0,5}/", $new, $search1037);

and:和:

preg_match_all("/1037(.*?{0,5})/", $new, $search1037);

but, I don't know how to use regular expressions correctly.但是,我不知道如何正确使用正则表达式。

I hope someone could help me!我希望有人可以帮助我!

Thank's a lot!非常感谢!

Use, \\d{6} represents 6 numbers使用,\\d{6}代表6个数字

preg_match_all("/1037(\d{6})/", $new, $search1037);

returns an array with返回一个数组

array(
    0   =>  array(
        0   =>  1037354607
    ),
    1   =>  array(
        0   =>  354607
    )
)

Check this demo检查这个演示

Since you're concerned with finding a resource-friendly solution, you may be better off not using preg_match .由于您关心的是寻找资源友好的解决方案,因此最好不要使用preg_match Regular expressions tend to require more overhead in general, as discussed in this SO question .正则表达式通常需要更多的开销,如this SO question中所述

Instead, you could use strstr() :相反,您可以使用strstr()

$string = strstr($string,'1037');

Which will return the first instance of '1037' in $string , along with everything following it.这将返回$string中 '1037' 的第一个实例,以及它后面的所有内容。 Then, use substr() :然后,使用substr()

$string = substr($string,4,6);

Which returns the substring within $string starting at position 4 (where position 0 = 1 , position 1 = 0 , position 2 = 3 , position 3 = 7 , position 4 = beginning of 6 digits) and including 6 characters.它返回$string从位置 4 开始的子$string (其中位置 0 = 1 ,位置 1 = 0 ,位置 2 = 3 ,位置 3 = 7 ,位置 4 = 6 个数字的开头)并包括 6 个字符。

For fun, in one line:为了好玩,在一行中:

$string = substr(strstr($string,'1037'),4,6);

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

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