Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/243.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在从所有其他文本中删除换行符时,需要在预标记中保留换行符_Php_String Formatting - Fatal编程技术网

Php 在从所有其他文本中删除换行符时,需要在预标记中保留换行符

Php 在从所有其他文本中删除换行符时,需要在预标记中保留换行符,php,string-formatting,Php,String Formatting,我有用户提交的文本通过表单,可以有多个文本块在预标签。我需要删除所有换行符,而不删除PRE标记中的换行符,并保留任何其他用户格式。$input=//随便什么 $input = // whatever $tokenized_input = explode('<pre>', $input); for($i = 0; $i < count($tokenized_input); ++$i) { $substrings = split('</pre>', $token

我有用户提交的文本通过表单,可以有多个文本块在预标签。我需要删除所有换行符,而不删除PRE标记中的换行符,并保留任何其他用户格式。

$input=//随便什么
$input = // whatever

$tokenized_input = explode('<pre>', $input); 
for($i = 0; $i < count($tokenized_input); ++$i) {
  $substrings = split('</pre>', $tokenized_input[$i]);
  if (!empty($substrings)) {
    $substrings[count($substrings) - 1] = str_replace("\n", '', $substrings[count($substrings) - 1]);
  }
  $tokenized_input[$i] = implode('</pre>', $substrings);
}

$output = implode('<pre>', $tokenized_input);
$tokenized_input=explode(“”,$input); 对于($i=0;$i
注意,我没有测试这个。它还假设:
-您的
标记都是小写的,没有属性

-您正在尝试仅删除换行符,而不是
\r\n

您需要在此处使用条件子模式。假设已删除


此代码在字符串中的
标记之间搜索0个或多个出现的文本,如果找到,则抓取文本,直到
标记
。当找到第一个
\n
时,搜索的单个迭代停止,然后用第一个捕获的组替换匹配的文本(即
\n
之前的文本)。

用户正在添加?这是来自textarea还是像ck这样的WYSIWYG编辑器?是的,用户正在textarea中添加pre…如果用户需要格式化选项,wysiwygi不会使用CKEditor。简单…而且工作…非常好!我的想法甚至不接近这种解决方案。非常感谢!谢谢Sam…我尝试了你的代码,它看起来很有效,但我想我会使用anubhava提供的答案,因为它的代码少了一点。
$str = "abc \nfoo\n <pre>123\ndef\nabc\n</pre>qwer\nttt\n bbb";
$p = '~((<pre>)(?(2).*?</pre>)(?:[^\n]*?))*?\n~smi';
$s = preg_replace($p, "$1", $str);
var_dump($s);
string(42) "abc foo <pre>123
def
abc
</pre>qwerttt bbb"