2013-10-21 24 views
2

我试图从数据库文本条目中检索第一句和最后一句。高级的第一句和最后一句功能

我在这个例子中,做工精细代码:

$text = "He was doing ok so far, but this one had stumped him. He was a bit lost..." 

功能:

function first_sentence($content) { 
$pos = strpos($content, '.'); 
if($pos === false) { 
    return $content; 
    } 
else { 
return substr($content, 0, $pos+1); 
} 
} // end function 

// Get the last sentence 

function last_sentence($content) { 
$content = array_pop(array_filter(explode('.', $content), 'trim')); 
return $content; 
} // end function 

最后一句功能考虑任何尾随...的在的结束句子,但都不能应对以下内容:

$text = "Dr. Know-all was a coding master, he knew everything and was reputed the world over. But the Dr. was in trouble..." 

结果: Fi第一句:Dr. 最后一句:遇到麻烦

我需要修改函数来考虑'Dr.'和其他这样的缩写,如果这是可能的,所以最后的文本变量会出现为:

第一句:Dr. Know-all是一个编码大师,他知道一切,并被全世界誉为 最后一句:但是博士遇到麻烦

可以这样做吗?任何帮助非常感谢!

+1

当一个句子以'...'结尾时,你会怎么做? –

+0

好点! ...或者确实是'!'。我还没有那么远:) 现在它会返回“第一句话是个问题吗?是的。”我现在可以接受这一点,因为我认为越多越好,但是我可能不得不稍后再说,除非有人想把它放在这里!感谢那。 –

+0

基本上,如果你想接受任意的英文文本,恐怕你将不得不处理一长串特殊情况。对于程序员来说,我会像[语言学家](http://linguistics.stackexchange.com/)一样成为一个问题。 –

回答

0

您可以检查您的substr长度,并且只在长度超过3个字符(包括点数)时才会返回。如果它不大或相等,你可以使用白名单,以免偶然发现诸如“不”,“我”,“我们”,“哦”等词......拼字游戏字典应该能够帮助你:)

1

也许你想过这样..

,你可以做一个函数来编码/解码您搜索的句子前$content;

function encode_content($content){ 
    return $encoded_content = str_replace("Dr.", "Dr#;#", $content); 
} 

你获取的句子后,再进行解码:

function decode_content($content){ 
    return $encoded_content = str_replace("Dr#;#", "Dr." , $content); 
} 
+0

谢谢!我已经选择了这个,它工作得很好:D –

+0

@MrC,我知道它没有优化..但有一些变化,你可以添加例外,如'...',''','先生。 '...只需在返回字符串之前添加'$ encoded_content = str_replace(“Mr。”,“Mr#;#”,$ encoded_content);''的每个异常行!希望能帮助到你! – Lan

2

您可以通过replacing排除某些字它们。

<? 

function first_sentence($content) { 
$pos = strpos($content, '.'); 
if($pos === false) { 
    return $content; 
    } 
else { 
return substr($content, 0, $pos+1); 
} 
} // end function 

// Get the last sentence 

function last_sentence($content) { 
$content = array_pop(array_filter(explode('.', $content), 'trim')); 
return $content; 
} // end function 

$text = "Dr. Know-all was a coding master, he knew everything and was reputed the world over. But the Dr. was in trouble..."; 

$tmp = str_replace("Dr.","Dr____",$text); 
echo $tmm ."\n"; 
echo str_replace("Dr____","Dr.",first_sentence($tmp))."\n"; 
echo str_replace("Dr____","Dr.",last_sentence($tmp)); 

?> 

WORKING CODE

0

只是回答我的问题,把一些新的功能一起给出的答案后,至今

function encode_text($content){ 
    $search = array("Dr.", "i.e.", "Mr.", "Mrs.", "Ms."); // put our potential problems in an array 
    $replace = array("Dr#;#", "i#e#", "Mr#;#", "Mrs#;#", "Ms#;#"); // make them good for first and last sentence functions 
    $encoded_content = str_replace($search, $replace, $content); 
    return $encoded_content; 
} // end encode 

然后,我们只是交换了搜索和周围替换变量,使我们的解码功能。现在,它们可以用于上面的第一句和最后一句话功能,并且它很有魅力。添加东西到阵列很简单,想到什么是适当的添加寿是不那么:)

干杯!