[英]Remove newlines inside <p> blocks
I have a string like this: 我有一个像这样的字符串:
<p>Here some text
another line</p>
<p>Another paragraph
another line</p>
What I want is something like following : 我想要的是如下内容:
<p>Here some text another line</p>
<p>Another paragraph another line</p>
Basically I want to remove new line character from the string within paragraph tags not anywhere else. 基本上,我想从段落标记中的字符串中删除换行符,而不是其他任何地方。
Please help. 请帮忙。 Thanks in advance. 提前致谢。
You want to use preg_replace. 您要使用preg_replace。
$string = "<p>Here some text
another line</p>
<p>Another paragraph
another line</p>
<p>test
123</p>
blah";
$pattern = '/<p>([^\n]+)\n+([^\n]+)/iS';
$replacement = "<p>$1 $2";
$paragraphs = explode("</p>",$string);
for ($i = 0; $i < count($paragraphs); $i++) {
$paragraphs[$i] = preg_replace($pattern, $replacement, $paragraphs[$i]);
}
$string = implode("</p>", $paragraphs);
echo $string . "\n";
devNoise
, your code works great unless there are multiple lines \\n
. devNoise
,除非有多行\\n
否则您的代码效果很好。 I'm sure there's a better way to do this with regexp than what I'm posting here, but here it is: 我敢肯定,使用regexp可以实现比我在这里发布的更好的方法,但是这里是:
$string = "<p>Here some text
another line</p>
<p>Another paragraph
another line</p>
<p>test
123</p>";
$paragraphs = explode("</p>",$string);
for ($i=0;$i<strlen($string);$i++) {
if (strstr($string[$i].$string[$i+1].$string[$i+2],"<p>")) {
$replace_on = 1;
}
if (strstr($string[$i].$string[$i+1].$string[$i+2].$string[$i+3],"</p>")) {
$replace_on = 0;
}
if ($replace_on==1) {
if (strstr($string[$i],"\n")) {
$new_string .= " ";
} else {
$new_string .= $string[$i];
}
} else {
$new_string .= $string[$i];
}
}
echo $new_string;
This should do what you want: 这应该做您想要的:
If text only contains paragraphs 如果文本仅包含段落
$string = "<p>Here some text
another line</p>
<p>Another paragraph
another line</p>";
$output = '';
$paragraphs = array_filter(explode("</p>", $string));
foreach ($paragraphs as $block) {
$output .= str_replace(array("\r", "\n"), '', $block);
}
var_dump($output); //<p>Here some textanother line</p><p>Another paragraphanother line</p>
If text contains multiple tags 如果文本包含多个标签
$string = "<p>Here some text
another line</p>
<img src=\"/path/to/file.jpg\";
<div id=\"test\">
<p>Another paragraph
another line</p>
</div>";
preg_match_all('~<p>(.+?)</p>~si', $string, $paragraphs);
foreach ($paragraphs[0] as $block) {
$output = '';
if (strlen($block)) {
$output = str_replace(array("\r","\n"), '', $block);
$string = str_replace($block, $output, $string);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.