简体   繁体   中英

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:

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

The problem is, the string is about 50.000 up to 1.000.000 characters long. 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

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 . Regular expressions tend to require more overhead in general, as discussed in this SO question .

Instead, you could use strstr() :

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

Which will return the first instance of '1037' in $string , along with everything following it. Then, use 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.

For fun, in one line:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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