在正则表达式中转义字符“\”(在大括号之间查找文本)

时间:2015-12-17 09:07:14

标签: php regex escaping

我当前的任务是转换字符串,并将“{}”之间的文字替换为

中提到的任何字符

例如,字符串:a {b | c} d {e | f} h,可能的结果:

'abdeh'
'abdfh'
'acdeh'
'acdfh'

此刻,我有一个功能

function producePatStr($str) {

    return preg_replace_callback('/{+(.*?)}/', function($matches) {

        $separated_chars = explode("|", $matches[1]);

        return $separated_chars[array_rand($separated_chars)]; 


    }, $str);

哪个工作正常,但是你可以帮我编辑我的正则表达式,“忽略”开放括号,如果它之前有转义字符“\”,就像那样:

a{b|c}d\{e|f}h

结果应该是这样的:  abd {e | f} h或acd {e | f} h

2 个答案:

答案 0 :(得分:1)

试试这个,应该适合你

function producePatStr($str) {
    return str_replace('\{', '{', preg_replace_callback('/[^\\\]{([^}]*)}/', function($matches) {
        $separated_chars = explode("|", $matches[1]);
        return $separated_chars[array_rand($separated_chars)]; 
    }, $str)
    );
}

$text = 'a{b|c}d\{e|f}h';
$output = producePatStr($text);
var_dump($output);

答案 1 :(得分:0)

   <!DOCTYPE html>
    <html>
    <head>
    <title>ABCD</title>
    <link rel="stylesheet" href="CSS/style.css" type="text/css">
    </head>
    <body>
    <div class="container">
    <header class="cf">
    <div class="Pull-Left">This Is The Main Title</div>
    <div class="Pull-Right">***Some Text***</div>
    </header>
    
      </br></br></br></br></br></br></br></br>
      </br></br></br></br></br></br></br></br>
      </br></br></br></br></br></br></br></br>
    
    <footer class="cf">
    <div  class="Pull-Left">This Is The Footer</div>
    </footer>
    
    </div><!--Container-->
    
    </body>
    </html>

你可以使用(?<!\\){[^}]*} 来查看相同的内容。参见演示。

https://regex101.com/r/fM9lY3/44