2010-03-29 84 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]; 
}