2015-07-12 62 views
3

所以我写了下面的代码来显示句子中第四个句号/句点之后的单词。PHP分解显示分隔符

$text = "this.is.the.message.seperated.with.full.stops."; 
$limit = 4; 

    $minText = explode(".", $text); 

    for($i = $limit; $i < count($minText); $i++){ 
     echo $minText[$i]; 
    } 

该算法正在工作,它显示了第四个“。”后面的句子的其余部分。句号/句号......我的问题是输出结果并没有在句子中显示句号,因此它显示的只是文本而没有正确的标点符号。“ ....有人可以请帮我解决如何修复代码以显示全停/期间?

非常感谢

+0

你想看到在年底的话,或只是一个之间存在的所有时间? –

+0

你能说明你需要什么来避免一些混淆吗?例如 - 你需要“分离。完全停顿”。或者“......分开。完全停顿”。或者是其他东西? – Endijs

回答

1

你可以试试这个...

for($i = $limit; $i < count($minText); $i++){ 
     echo $minText[$i]."."; 
    } 

通知,echo命令//年底增加的时期。 “”;

+0

这解决了我的问题......作为魅力@superkayrad工作;) – Eric

1
$text = "this.is.the.message.seperated.with.full.stops."; 
$limit = 4; 
$minText = explode(".", $text); 
for($i = $limit; $i < count($minText); $i++){ 
    echo $minText[$i]."."; 
} 
1

如果你想打破它在单词之间的时间间隔,但保持一个是在结束为实际的标点符号,你可能需要使用preg_replace()的周期转换成另一种字符,然后爆炸它。

$text = "this.is.the.message.seperated.with.full.stops."; 
$limit = 4; 

//replace periods if they are follwed by a alphanumeric character 
$toSplit = preg_replace('/\.(?=\w)/', '#', $text); 

    $minText = explode("#", $toSplit); 

    for($i = $limit; $i < count($minText); $i++){ 
     echo $minText[$i] . "<br/>"; 
    } 

这将产生

seperated 
with 
full 
stops. 

当然,如果你只是单纯的想打印所有的句号,然后将它们添加在您echo期限之后。

echo $minText[$i] . "."; 
1

而是拆分输入字符串,然后遍历它,你可以用strpos()函数改变偏移参数找到分隔符(。)在字符串中的第n个位置。

然后,它只是从我们刚刚确定的位置打印子字符串的问题。

<?php 

$text = "this.is.the.message.seperated.with.full.stops."; 
$limit = 4; 
$pos = 0; 

//find the position of 4th occurrence of dot 
for($i = 0; $i < $limit; $i++) { 
    $pos = strpos($text, '.', $pos) + 1; 
} 

print substr($text, $pos); 
1

如果需要输出“ seperated.with.full.stops”,那么你可以使用:

<?php 

$text = "this.is.the.message.seperated.with.full.stops."; 
$limit = 4; 

$minText = explode(".", $text); 
$minText = array_slice($minText, $limit); 

echo implode('.', $minText) . '.';