2010-03-29 46 views
-1

需要獲取給定文本的前10個單詞和後10個單詞。我的意思是需要在關鍵字前面開始10個單詞,並在關鍵詞後面以10個單詞結束。Php字符串處理技巧

給定的文本:「二十三」

主要的竅門:有一些HTML標籤等內容..標籤需要保持該標籤僅此內容。需要從10before顯示的話 - 10after

含量爲波紋管:

removed 

謝謝

+0

莫非你舉了一個例子來說明你期望的輸出s功能? – Andy 2010-03-29 09:53:57

+0

你能給你的例子添加換行符嗎?現在很難閱讀。 – 2010-03-29 09:59:17

+0

@Dam - 請爲您的問題找到另一個示例文本。 – user187291 2010-03-29 11:41:04

回答

1

此方法假設詞語僅由空格(未製表符,換行符或其它空格),並分離取決於PHP庫函數「strip tags」,它可能採用格式良好的HTML(根據我的經驗,這是一個糟糕的假設)。

$string_content = strip_tags($html_content); 
$start_cursor = $end_cursor = strpos($string_content, 'Twenty-three'); 
for($i = 0; $i < 10; $i++) { // rewind backwards until we find 10 spaces 
    $start_cursor = strrpos($string_content, ' ', $start_cursor); 
} 
for($i = 0; $i <= 10; $i++) { // skip forward until we find eleven spaces 
    $end_cursor = strpos($string_content, ' ', $end_cursor); 
} 
$result_string = substr($string_content, $start_cursor, $end_cursor - $start_cursor); 

未經檢驗的,但我相信這是一個有效的方法

可選,可以消毒的空白:

$string_content = strip_tags($html_content); 
$string_content = preg_replace("/\s+/", " ", $string_content); // replace any number of adjacent whitespace characters with a single space 
+0

注意:如果找到相鄰的空格,這將顯示少於10個單詞。有辦法慢,如果你想這樣做更靈活的方式... – David 2010-03-29 10:05:02

+0

你好謝謝你,但「strpos」只能得到第一個字符串只有它沒有采取「第二十三條」全我想是這樣的位置... – Subha 2010-04-05 07:14:08

+0

嗨感謝您的幫助 用strip_tags在PHP 同樣喜歡有需要MySQL使用我不希望得到具有HTML標籤內的keyowrd 查詢行WHERE'text' =「關鍵字」 – Subha 2010-04-12 09:01:59

0
<?php 
$find = 'Twenty-three'; 
$words = explode(' ', $string); 
$wordsLimit = 10; // 10 words 

// Number of words 
$wordsLength = count($words); 

// Find the position of the word ($find) inside the phrase 
$findPosition = (in_array($find, $words)) ? array_search($find, $words) : 0; 

// Cut the phrase 
$beforeIndex = max(0, ($findPosition - $wordsLimit)); 
$afterIndex = min($wordsLength, ($findPosition + $wordsLimit + 1)); 
$words = array_slice($words, $beforeIndex, $afterIndex); 

// Display the final phrase 
$string = join(' ', $words); 
echo $words; 
?> 
0

這應該做的伎倆:

function getSurrounding($string, $needle){ 
    // Strip html tags 
    $string = strip_tags($string); 
    // Concat blank characters 
    $string = preg_replace('`\\s+`', ' ', $string); 
    // Use some regexp magic 
    preg_match_all('`(?:[^ ]+){10}'.$needle.'(?: [^ ]+){10}`', $string, $blocks); 
    return $blocks[0]; 
}