2013-03-09 67 views
0

我嘗試過並嘗試過,但我很難過。假設我有以下情形:從基於關鍵字的固定長度的文本中提取字符串

$string = "Jenny's garden is one of the best in town, it has lush greens and colorful flowers. With what happened to her recently, she could use a new sprinkler system so that she does not have to over exert herself. Perhaps Joel can sell that extra bike to raise money or perhaps put up a garage sale."; 

$keyword = "recently"; 

$length = 136; 

// when keyword keyword is empty 
$result = "Jenny's garden is one of the best in town, it has lush greens and colorful flowers. With what happened to her recently, she could use a (snip)"; 

// when keyword is NOT empty 
$result = "(snip)it has lush greens and colorful flowers. With what happened to her recently, she could use a new sprinkler system so that she does not h(snip)"; 

我想要做的就是串的摘錄於$結果可能圍繞一個關鍵詞第一次出現(如果存在的話),如圖所示。我很困惑如何使用substr和strpos在php中實現這一點。幫幫我?

+0

而且[你有什麼嘗試](http://whathaveyoutried.com)? – Havelock 2013-03-09 07:48:34

+1

我已經嘗試過幾種方法,但是我並不擅長計算所有這些,這只是輕描淡寫。我一直在試圖找到字符串位置,然後從長度的一半中減去它,然後通過子字符串運行它。這取得了我想要的一些段落的結果,但對於許多具有$關鍵字的結果來說,提取的字符串非常短。由於亞當的答案是完美無缺的,所以我不敢傳播我可怕的編碼習慣。但是,相信我,我嘗試過。我不是一個跳入其中並且讓別人爲我工作的人。我根本無法理解它背後的邏輯。 – JuniePHP 2013-03-09 09:12:14

+0

在原始問題中提供所有信息將幫助您更快地獲得更多答案。 – Havelock 2013-03-09 09:40:08

回答

1

這應該對你所需要的工作:

if ($keyword != "") { 
    $strpos = strpos($string, $keyword); 
    $strStart = substr($string, $strpos - ($length/2), $length/2); 
    $strEnd = substr($string, $strpos + strlen($keyword), $length/2); 

    $result = $strStart . $keyword . $strEnd; 
} 
else { 
    $result = substr($string, 0, $length); 
} 

下面是測試代碼我使用:

<?PHP 
$string = "Jenny's garden is one of the best in town, it has lush greens and colorful flowers. With what happened to her recently, she could use a new sprinkler system so that she does not have to over exert herself. Perhaps Joel can sell that extra bike to raise money or perhaps put up a garage sale."; 

$keyword = "recently"; 

$length = 136; 

if ($keyword != "") { 
    $strpos = strpos($string, $keyword); 
    $strStart = substr($string, $strpos - ($length/2), $length/2); 
    $strEnd = substr($string, $strpos + strlen($keyword), $length/2); 

    $result = $strStart . $keyword . $strEnd; 
} 
else { 
    $result = substr($string, 0, $length); 
} 

echo $result; 
?> 

這裏是在呼應結果:

有鬱鬱蔥蔥的綠色和五顏六色的鮮花。隨着最近發生了什麼給她,她可以用一個新的自動噴水滅火系統,使她不必

編輯:修正了我的代碼一對夫婦的錯誤...

注:此選項將顯示一個$結果即136個字符+關鍵字的長度。如果你想要它只有136,添加$length = 136 - strlen($keyword);

+1

亞當你是一個天才,我接近了,但它只對字符串開始的關鍵字起作用。我根本不明白這一切的邏輯。我從來沒有想過要分開開始和結束工作,並加入他們。作品像一個魅力! – JuniePHP 2013-03-09 09:14:57

+0

太棒了!很高興我能幫上忙。 – 2013-03-09 09:17:08

相關問題