【问题标题】:Regex/PHP: How to remove linebreaks from within a special pattern正则表达式/PHP:如何从特殊模式中删除换行符
【发布时间】:2013-12-18 09:07:30
【问题描述】:

我在从模板文件的标记中删除换行符时遇到了另一个问题 - 我必须解析的模板可能如下所示:

<html>
<style>
body { color: black }
div {
   background-color:#fff; 
}
 <!-- i need to remove the line breaks within {_WP_token[*]} for parsing //-->
<h4>{_WP_token[id="42";class="foo"; style="border:4px solid 
green;padding:20px"; onclick="(this.value=confirm('foo'));"]}</h4>

<script>
    function() {
        console.log('my foo is my castle');
    }
</script>

我尝试了自己但没有取得突破。我刚刚成功地创建了一个贪婪的,它吃掉了令牌的前半部分 - 这里是:

preg_replace("/(\{_(.*?)(.*\s))/ix", "[LB REMOVED]", $htmlTemplate);

返回

<html>
<style>
body { color: black }
div {
    background-color:#fff; 
}
<!-- it just ate up the first half of my token ! //-->
<h4>[LB_REMOVED]green;padding:20px"; onclick="(this.value=confirm('foo'));"]}</h4>
<script>
function() {
   console.log('my foo is my castle');
}
</script>

我在这里做了一个小提琴:http://www.phpliveregex.com/p/2EZ

非常感谢您。

最好的问候, 卢波

【问题讨论】:

    标签: php regex line-breaks


    【解决方案1】:

    试试:

    $newString = preg_replace("/[\n\r]/","[LB_REMOVED]", $originalString);
    

    【讨论】:

    • 但我只想删除此特殊模式中的换行符:"{_[A-Za-z][* (...ONLY_REMOVE_LINEBREAKS_FROM_THIS_PART...) ]\}"
    【解决方案2】:

    我不确定我是否理解正确。如果你想改变

    <h4>{_WP_token[id="42";class="foo"; style="border:4px solid 
    green;padding:20px"; onclick="(this.value=confirm('foo'));"]}</h4>
    

    进入

    <h4>{_WP_token[id="42";class="foo"; style="border:4px solid green;padding:20px"; onclick="(this.value=confirm('foo'));"]}</h4>
    

    那你就可以用这个了

    \{_(.*)[\r\n]+
    

    并替换为 $1,See it on Regexr

    preg_replace("/\{_(.*)[\r\n]+/", "$1", $htmlTemplate);
    

    我删除了你所有的修饰符,因为你不使用它们。 See Modifiers doc

    【讨论】:

      猜你喜欢
      • 2016-05-26
      • 2020-12-22
      • 1970-01-01
      • 2011-07-01
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 2014-05-05
      相关资源
      最近更新 更多