2012-11-01 46 views
0

請考慮我們有一個主串和一個搜索字符串。如何從主線串得到strpos()匹配的字符串

<?php 
$mystring = ',1,123,167,778,456'; 
$findme = '123'; 
$pos = strpos($mystring, $findme); 
if ($pos === false) { 
echo "The string '$findme' was not found in the string '$mystring'"; 
} else { 
echo "The string '$findme' was found in theenter code here string '$mystring'"; 
echo " and exists at position $pos"; 
} 
?> 

如果我們發現有123那麼它做工精細,並給予回答字符串中找到,但如果我們給$findme值「12」,那麼它也給予正面的回答。 我想要如果strpos()匹配一個字符串,那麼這個匹配字符串保存在一個變量像。

strpos(',1,123,167,778,456','12'); 

那麼123在可變商店

$string_from_main_string = '123'; 
+0

由於您已經在使用給定的字符串進行搜索,因此提取相同的字符串有什麼意義。你可以使用'substr($ mystring,$ pos,strlen($ findme))'來獲得它。 – air4x

+0

@ air4x因爲你看到我有一個空值在開始,所以它不能給予正確的字符串 –

回答

1

最好使用explodein_array對於這樣的任務

$mystring = ',1,123,167,778,456'; 
$findme = '123'; 

$arr = explode(',',$mystring); 
if(in_array($findme,$arr)){ 
    echo "Found"; 
} 
else{ 
    echo "Not Found"; 
} 
+0

使用in_array執行時間增加 –

0

我認爲,要追加值原字符串,如果strpos的值是正數但在字符串中不完全可用:

$a = "1,123,456,746"; 
$a_arr = explode(",", $a); 
$findme = "123"; 
if (strlen(strpos($a, $findme)) > 0){ 
if(in_array($findme, $a_arr)){ 


}else{ 
    $a .= ",".$findme; 
    array_push($a_arr, $findme); 
} 
}