简体   繁体   English

在两个定界符之间分割字符串

[英]Split string between two delimiters

I'm trying to match a string in a HTML source code with starting <!--sliderStart--> and ending <!--sliderEnd--> 我想在HTML源代码的字符串匹配第<!--sliderStart-->和结束<!--sliderEnd-->

Example1: 范例1:

<!--sliderStart-->
<p>blah</p>
<p>blah2</p>
<!--sliderEnd-->

Example2: 范例2:

<!--sliderStart--><p>blah</p><p>blah2</p><!--sliderEnd-->

This is my pattern, but it's not working efficiently: 这是我的模式,但是效率不高:

$pattern = "/<!--sliderStart-->[^\n]+(.*?)<!--sliderEnd-->/";

What's the exact pattern for this matching? 匹配的确切模式是什么?

Why are you using [^\\n]+ in your regex? 为什么在正则表达式中使用[^\\n]+ That tells the regex engine not to match newlines, which you do want to match. 这告诉正则表达式引擎匹配换行符,其中想匹配。

Simply get rid of it, and you're good to go: 只需摆脱它,您就可以开始:

$pattern = "/<!--sliderStart-->(.*?)<!--sliderEnd-->/s";

Update : Don't forget the s modifier at the end, so that the . 更新 :不要忘了最后加上s修饰符,以便使用. also matches newlines. 也匹配换行符。
Thanks @Palladium. 谢谢@钯。

Regular expression dots don't match newlines unless you tell them to. 除非您告诉正则表达式点,否则它们不与换行符匹配。 You need a s modifier at the end of your regex, like so: 您需要在正则表达式的末尾添加一个s修饰符,如下所示:

$pattern = '/<!--sliderStart-->(.*?)<!--sliderEnd-->/s';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM