需要获取给定文本的前10个单词和后10个单词。我的意思是需要在关键字前面开始10个单词,并在关键词后面以10个单词结束。Php字符串处理技巧
给定的文本:“二十三”
主要的窍门:有一些HTML标签等内容..标签需要保持该标签仅此内容。需要从10before显示的话 - 10after
含量为波纹管:
removed
谢谢
需要获取给定文本的前10个单词和后10个单词。我的意思是需要在关键字前面开始10个单词,并在关键词后面以10个单词结束。Php字符串处理技巧
给定的文本:“二十三”
主要的窍门:有一些HTML标签等内容..标签需要保持该标签仅此内容。需要从10before显示的话 - 10after
含量为波纹管:
removed
谢谢
此方法假设词语仅由空格(未制表符,换行符或其它空格),并分离取决于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
<?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;
?>
这应该做的伎俩:
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];
}
莫非你举了一个例子来说明你期望的输出s功能? – Andy 2010-03-29 09:53:57
你能给你的例子添加换行符吗?现在很难阅读。 – 2010-03-29 09:59:17
@Dam - 请为您的问题找到另一个示例文本。 – user187291 2010-03-29 11:41:04