Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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_Regex_Newline - Fatal编程技术网

php正则表达式-仅删除前后没有空格的换行符

php正则表达式-仅删除前后没有空格的换行符,php,regex,newline,Php,Regex,Newline,我需要清理那些即使在单词内也添加了无效换行符的文本,以及在单词之间添加了有效换行符的文本,这样就有了一个前导或训练空间 使用php,可以尝试从由字符包围的多行文本中删除这些换行符,这意味着前后没有空格 $textbefore = "text has newlines in wo\nrds and normal newlines \n bewtween words and again in wo\nrds"; $textafter = "text has newlines in words and

我需要清理那些即使在单词内也添加了无效换行符的文本,以及在单词之间添加了有效换行符的文本,这样就有了一个前导或训练空间

使用php,可以尝试从由字符包围的多行文本中删除这些换行符,这意味着前后没有空格

$textbefore = "text has newlines in wo\nrds and normal newlines \n bewtween words and again in wo\nrds";
$textafter = "text has newlines in words and normal newlines \n bewtween words and again in words";
试过这个

$pattern="/(.{2}\n.{1})/m";
我尝试了所有可能的模式,但在最好的情况下,只有第一次出现的匹配


非常感谢您的任何想法。

您可以将其简化为以下正则表达式:

$textafter = preg_replace( "/(?<=\S)\n|\n(?=\S)/", '', $textbefore);

您可以使用负向前看和负向后看:

/(?<!\s)\n(?!\s)/
/(?
它将匹配前后没有空间的新行


稍微颠倒一下问题,如果换行符的两边都是文本,那么换行符只会“无效”吗?如果它在字符串的开头或结尾呢?我想你假设正则表达式懂语言。定义“单词”取决于你自己视觉上注意到一种语言模式并不一定意味着它可以被翻译成正则表达式,特别是当涉及到“单词”时。
/(?<!\s)\n(?!\s)/