[英]PHP Find all substrings within a string that contain a period and end with a space
[英]Find all substrings within a string with overlap
您好,我正在嘗試查找字符串中所有重疊的子字符串,這是我的代碼,它只查找非重復的 ACA。
$haystack = "ACAAGACACATGCCACATTGTCC";
$needle = "ACA";
echo preg_match_all("/$needle/", $haystack, $matches);
您正在使用echo
打印preg_match_all
的返回值。 也就是說,您只顯示找到的匹配項數。 你可能想做的是print_r($matches);
, 像這樣:
$haystack = "ACAAGACACATGCCACATTGTCC";
$needle = "ACA";
preg_match_all("/$needle/", $haystack, $matches);
print_r($matches);
Output:
Array
(
[0] => Array
(
[0] => ACA
[1] => ACA
[2] => ACA
)
)
如果你真正關心的是它只計算了一次ACACA
,那么,關於這一點需要說明三點:
也就是說,如果你想計算兩次,你可以這樣做:
echo preg_match_all("/(?=$needle)/", $haystack, $matches);
Output:
4
這是一個腳本,用於查找 substring 的所有出現,以及重疊的出現。
$haystack = "ACAAGACACATGCCACATTGTCC";
$needle = "ACA";
$positions = [];
$needle_len = strlen($needle);
$haystack_len = strlen($haystack);
for ($i = 0; $i <= $haystack_len; $i++) {
if( substr(substr($haystack,$i),0,$needle_len) == $needle){
$positions[]=$i;
}
}
print_r($positions);
Output: Array ( 0, 5, 7, 14 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.