当前位置: 动力学知识库 > 问答 > 编程问答 >

PHP regex - pattern does not match

问题描述:

I am trying to replace all body and html selectors with a custom class. (Later on the html content will be displayed in a custom container and available css should not effect the main Site.)

Here is a what I've tried:

$data = "html body { color: red; }\nbody html { color: red; }\nhtml, body { color: red; }\nbody, html, .body table, #html-TemplateContainer {\nbackground-color:#eee;\n}";

echo "<pre>".preg_replace('/(^|[,}\s]+)(body html|html body|html|body)([,.{\s]*)/is', '$1'.'.foo'.'$3', $data)."</pre>";

Which prints:

.foo { color: red; }

.foo { color: red; }

.foo, body { color: red; }

.foo, html, .body table, #html-TemplateContainer {

background-color:#eee;

}

I do not understand why in line 3 and 4 the body and html (scnd selector) is not replaced, for my understanding it should match the regex?!

网友答案:
 You should try this...
 =========================>


  echo  "<pre>".preg_replace('/(^|#|.|\s]+)(body html|html body|html|body)([^,.{\s]*)/is', 
  '$1'.'.foo'.'$3', $data)."</pre>";
网友答案:

Thanks to cbuckley, i had to use lookahead and lookbehind and now it works fine ;) I made some improvements so it may match now any possibilities.

working code:

$data = "html body { color: red; }\nhtml *.class { color: red; }\nhtml,body { color: red; }\nhtml[dir=\"rtl\"], body, .body table, #html-container\n{\n    background-color:#eee;\n}";
echo "<pre>".preg_replace('/(?<=^|[,}\]\s])(\*\s+html\s+body|\*\s+body\s+html|html\s+\*\s+body|html\s+body\s+\*|body\s+\*\s+html|body\s+html\s+\*|\*\s+html|\*\s+body|html\s+\*|html\s+body|body\s+\*|body\s+html|\*|html|body)(?=[,.{\[\s]|$)/is', '.foo', $data)."</pre>";

original css:

html body { color: red; }
html *.class { color: red; }
html,body { color: red; }
html[dir="rtl"], body, .body table, #html-container
{
    background-color:#eee;
}

modified css:

.foo { color: red; }
.foo.class { color: red; }
.foo,.foo { color: red; }
.foo[dir="rtl"], .foo, .body table, #html-container
{
    background-color:#eee;
}

Multiple occurrence of the same selector can be filtered out afterwards.

分享给朋友:
您可能感兴趣的文章:
随机阅读: