这是一个字符串。没有任何新的线条。我需要换行 段落。我决定使用跟随停止,即点后跟白色 空间来制作段落中每两个点出现的段落 字符串。
在上面的虚拟字符串中,正如我所描述的那样,我需要在每次出现.
时将字符串拆分,后面跟一个空格来添加\n
或<p>
标记。
我知道的唯一方法是explode
。然后在数组内循环并在每两个元素后继续。但是,它将分割字符串,无论其是否跟随空格。
此外,此过程可能存在性能问题。
我需要知道是否有办法更准确,更有效率。
$arr = explode('.',$mystring);
$output = '';
for ($i=0; $i < count($arr); $i++){
$output .= $arr[$i].'. ';
if (isset($arr[$i+1])){
$output .= $arr[$i+1].'. '."\n";
$i++;
}
else{
$output .= '. '."\n";
}
}
换句话说,上面引用的字符串应该如下所示:
This is a string. Without any new lines.
I need the newlines to make paragraphs. I decided to use follow-stop i.e the dot followed by white space to make paragraphs every two occurance of those dots in the string.
答案 0 :(得分:2)
正则表达式方法怎么样?
$string = 'This is a string. Without any new lines. I need the newlines to make paragraphs. I decided to use follow-stop i.e the dot followed by white space to make paragraphs every two occurance of those dots in the string.';
preg_match_all('~((?:.+?\.){2})(.*)~', $string, $matches);
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] => This is a string. Without any new lines. I need the newlines to make paragraphs. I decided to use follow-stop i.e the dot followed by white space to make paragraphs every two occurance of those dots in the string.
)
[1] => Array
(
[0] => This is a string. Without any new lines.
)
[2] => Array
(
[0] => I need the newlines to make paragraphs. I decided to use follow-stop i.e the dot followed by white space to make paragraphs every two occurance of those dots in the string.
)
)
Regex101演示:https://regex101.com/r/iV1gR1/1
0
是整个发现的表达。 1
是第一个被捕获的组(也就是前2个句子)。 2
是剩下的内容。
实际上在重读问题时,你是否试图分裂每一句话?如果是这样,也许这就是你想要的:
$string = 'This is a string. Without any new lines. I need the newlines to make paragraphs. I decided to use follow-stop i.e the dot followed by white space to make paragraphs every two occurance of those dots in the string.';
preg_match_all('~(.+?[.?!])(?:\s+|$)~', $string, $matches);
print_r($matches[1]);
输出:
Array
(
[0] => This is a string.
[1] => Without any new lines.
[2] => I need the newlines to make paragraphs.
[3] => I decided to use follow-stop i.e the dot followed by white space to make paragraphs every two occurance of those dots in the string.
)
答案 1 :(得分:0)
{{1}}