简体   繁体   English

如何使用PHP在字符串中查找模式的位置?

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

I'm a newbie to php. 我是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 例如:如果$pattern = '/abcd/'$string = 'weruhfabcdwuir'则该函数应返回6,因为6是$string'abcd'起始索引

You can use strpos() for this. 您可以为此使用strpos()

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

If you're trying to match a regexp pattern (not a straight string), strpos() won't help you. 如果您尝试匹配一个正则表达式模式(不是直串),则strpos()将无济于事。 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: 相反,请使用preg_match() (如果您只想在第一个匹配项上进行匹配)或preg_match_all() (如果要匹配所有匹配项)和PREG_OFFSET_CAPTURE标志:

$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() : 使用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);

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

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