我嘗試過並嘗試過,但我很難過。假設我有以下情形:從基於關鍵字的固定長度的文本中提取字符串
$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中實現這一點。幫幫我?
而且[你有什麼嘗試](http://whathaveyoutried.com)? – Havelock 2013-03-09 07:48:34
我已經嘗試過幾種方法,但是我並不擅長計算所有這些,這只是輕描淡寫。我一直在試圖找到字符串位置,然後從長度的一半中減去它,然後通過子字符串運行它。這取得了我想要的一些段落的結果,但對於許多具有$關鍵字的結果來說,提取的字符串非常短。由於亞當的答案是完美無缺的,所以我不敢傳播我可怕的編碼習慣。但是,相信我,我嘗試過。我不是一個跳入其中並且讓別人爲我工作的人。我根本無法理解它背後的邏輯。 – JuniePHP 2013-03-09 09:12:14
在原始問題中提供所有信息將幫助您更快地獲得更多答案。 – Havelock 2013-03-09 09:40:08