2013-11-20 44 views
-5

我想要做的是搜索文本/長文本內等字:如何在文本中搜索字符串?

$txt = 'text das text dss text good text text bad text'; 

,我想在這個$txt搜索good text不用像stripos()或其他PHP函數,我想使用只需在PHP中使用for,並儘可能地創建最小循環。

我怎樣才能通過所有$txt尋找good text並得到它之後呢?

+0

甚至沒有正則表達式的功能呢? –

+0

http://stackoverflow.com/questions/2528736/how-to-iterate-loop-inside-a-string-searching-for-any-word-aftera-fixed-keyword –

+0

我真的不明白爲什麼DOWNGRADE! !這是一個真正的問題! – Abude

回答

2
<?php 
function findRemaining($needle, $haystack) { 
    $result = ''; 

    for ($i = 0, $found = false; isset($haystack[$i]); $i += 1) { 
    if (!$found) { 
     for ($j = 0; isset($haystack[$i + $j], $needle[$j]); $j += 1) { 
     if ($haystack[$i + $j] !== $needle[$j]) { 
      continue 2; 
     } 
     } 

     $found = true; 
    } 

    $result .= $haystack[$i]; 
    } 

    return $result; 
} 

$haystack = 'text das text dss text good text text bad text'; 
$needle = 'good text'; 

// string(23) "good text text bad text" 
var_dump(
    findRemaining($needle, $haystack) 
); 
+0

+1 ...好Yoshi :)你的回答太棒了!謝謝!你的做法是 – Abude

+0

檢查之後真有意思,你的結果withing自定義功能的var_dump是隻返回的第一個字母=>「G」 ... – Abude

+0

我改變了答案,給出瞭如何收集結果,並返回它的一個示例從一個函數。 – Yoshi

1
<?php 
    $txt = 'text das text dss text good text text bad text'; 
    $search = 'good text'; 

    $pos = -1; 

    $i = 0; 

    while (isset($txt{$i})) { 
    $j = 0; 

    $wrong = false; 

    while (isset($search{$j})) { 
     if ($search{$j} != $txt{$i + $j}) { 
     $wrong = true; 

     break; 
     } 

     $j++; 
    } 

    if (!$wrong) { 
     $pos = $i; 

     break; 
    } 

    $i++; 
    } 

    echo 'Position: '.$pos; // in your case it will return position: 23 
?> 
+0

謝謝你的回答!但我不想使用任何PHP函數來執行此操作,請不要使用strlen,substr?再次感謝! – Abude

+0

如何在不知道'$ txt'和'$ search'的長度的情況下爲''做些什麼?我可以使用'while'嗎? – Legionar

+0

是的,這是確定使用'while'確保 – Abude

-1

您可以在這裏使用preg_match。你想要關於這個的例子嗎?

+0

感謝您的回答!但只有isset()可以使用 – Abude

1

試試這個,讓我知道...

$txt = "text das text dss text good text text bad text"; 
function search_string($word, $text){ 
$parts = explode(" ", $text); 
$result = array(); 
$word = strtolower($word); 

foreach($parts as $v){ 

    if(strpos(strtolower($v), $word) !== false){ 
    $result[] = $v; 
    } 
} 
if(!empty($result)){ 
    return implode(", ", $result); 
}else{ 
    return "Not Found"; 
} 
} 
echo search_string("text", $txt); 
+0

感謝您的回答,但再次,我需要一個沒有PHP函數的實現......就像Yoshi的回答。謝謝你的努力! – Abude