简体   繁体   中英

How to find the position of a pattern in a string using PHP?

I'm a newbie to php. is there any function that can match a pattern in a given string and and return the index of the beginning of the pattern within that string? eg: if $pattern = '/abcd/' , $string = 'weruhfabcdwuir' then the function should return 6 since 6 is starting index of 'abcd' in $string

You can use strpos() for this.

http://php.net/manual/en/function.strpos.php

If you're trying to match a regexp pattern (not a straight string), strpos() won't help you. Instead, use preg_match() (if you only want to match on the first occurrence) or preg_match_all() (if you want to match all occurrences) and the PREG_OFFSET_CAPTURE flag:

$pattern = '/abcd/';
$string = 'weruhfabcdwuir';

preg_match($pattern, $string, $matches, PREG_OFFSET_CAPTURE);

// $matches[0][0][1] == 6, see PHP.net for structure of $matches
print_r($matches);

Example with more than one match using preg_match_all() :

$pattern = '/abcd/';
$string = 'weruhfabcdwuirweruhfabcdwuir';

preg_match_all($pattern, $string, $matches, PREG_OFFSET_CAPTURE);

// $matches[0][0][1] == 6
// $matches[0][1][1] == 20
print_r($matches);

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