簡體   English   中英

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

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

我是php的新手。 是否有任何功能可以匹配給定字符串中的模式並返回該模式在該字符串中的開頭的索引? 例如:如果$pattern = '/abcd/'$string = 'weruhfabcdwuir'則該函數應返回6,因為6是$string'abcd'起始索引

您可以為此使用strpos()

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

如果您嘗試匹配一個正則表達式模式(不是直串),則strpos()將無濟於事。 相反,請使用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);

使用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