我想要做的是搜索文本/長文本內等字:如何在文本中搜索字符串?
$txt = 'text das text dss text good text text bad text';
,我想在這個$txt
搜索good text
不用像stripos()
或其他PHP函數,我想使用只需在PHP中使用for
,並儘可能地創建最小循環。
我怎樣才能通過所有$txt
尋找good text
並得到它之後呢?
我想要做的是搜索文本/長文本內等字:如何在文本中搜索字符串?
$txt = 'text das text dss text good text text bad text';
,我想在這個$txt
搜索good text
不用像stripos()
或其他PHP函數,我想使用只需在PHP中使用for
,並儘可能地創建最小循環。
我怎樣才能通過所有$txt
尋找good text
並得到它之後呢?
<?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)
);
<?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
?>
試試這個,讓我知道...
$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);
感謝您的回答,但再次,我需要一個沒有PHP函數的實現......就像Yoshi的回答。謝謝你的努力! – Abude
甚至沒有正則表達式的功能呢? –
http://stackoverflow.com/questions/2528736/how-to-iterate-loop-inside-a-string-searching-for-any-word-aftera-fixed-keyword –
我真的不明白爲什麼DOWNGRADE! !這是一個真正的問題! – Abude