正则表达式:匹配两个标签(或两个星号)之间的换行符

RegEx: Match Linefeeds between two tags (or alternatively two asterisks)

希望你能帮助我。 我有以下字符串:

<floatingText>After Cesar had reported this, he \r\n
 jumped into his UFO and flew to space</floatingText>

我只想匹配标签之间的\r\n,因为我想删除换行符(用''代替)所以我需要匹配他们用正则表达式。 除了 <floatingText></floatingText>,我还可以使用星号* 作为分隔符,例如

*After Cesar had reported this, he \r\n
 jumped into his UFO and flew to space*
Story goes on ... with some text.
*Another section with \r\n\
a linefeed within asterisks*

以下是我试过的:

\*([\s\S]*?)\* 匹配 * 之间的所有内容,包括 * 直到下一个 * 出现。 https://regexr.com/5hmnm

(\*)[^<]*(\*) 匹配 * 之间的所有内容,包括,即使在(故事继续......)之间有一个部分,这不是我想要的。 https://regexr.com/5hmoe

希望您能帮帮我,我将不胜感激。

有几个选项,但更通用的是匹配定界符之间的所有文本,然后将匹配传递给替换函数,您可以在其中删除所有 CR 和 LF:

$text = "*After Cesar had reported this, he\r\n jumped into his UFO and flew to space*\r\nStory goes on ... with some text.\r\n*Another section with\r\na linefeed within asterisks*";
echo preg_replace_callback('~\*[^*]*\*~', function($x) { return str_replace(["\r","\n"], '', $x[0]); }, $text);
=> *After Cesar had reported this, he jumped into his UFO and flew to space*
Story goes on ... with some text.
*Another section witha linefeed within asterisks*

参见PHP demo

当你有标签时,你只需要使用其中之一

'~<floatingText>.*?</floatingText>~s'
'~<floatingText>[^<]*(?:<(?!/?floatingText>)[^<]*)*</floatingText>~'

作为正则表达式模式。