正则表达式仅在两个其他特定字符串之间查找特定字符串

时间:2014-02-14 21:58:15

标签: php html css regex

基本上,我需要在大约3000个文档中替换css类警报,因为它会破坏bootstrap css。我可以通过搜索(?<=class=")(.*)(?=")找到整个css类,但我不能通过使用(?<=class=".*)(alert)(?=.*")或类似的东西找到警报类。

基本上,给定一组数据:

<div class=" big alert solid">Alert alert</div>
<div class="alert solid">Alert alert</div>
<div class=" big solid">Alert alert</div>

我只想在class属性中找到文本提醒。

我有一种感觉,如果有一个可行的解决方案,它将涉及前瞻/后方的可选通配符。类似的东西:

(?<=class="(.)?)(.*)(?=(.)?")

3 个答案:

答案 0 :(得分:0)

您可以尝试这样的表达式:

(?<=class\s?=\s?")(.*?)alert(.*?)(?=")

然后替换占位符就像

$1$2

导致

<div class=" big  solid">Alert alert</div>
<div class=" solid">Alert alert</div>
<div class=" big solid">Alert alert</div>

答案 1 :(得分:0)

任何标记的正则表达式,例如divspanp

(<[A-Z][A-Z0-9]*\b[^>]*\bclass\s*=\s*"(?:|[^"]+))\balert\b((?:|[^"]+)")

Regular expression visualization

div代码的正则表达式:

(<div\b[^>]*\bclass\s*=\s*"(?:|[^"]+))\balert\b((?:|[^"]+)")

作为替代选择,请选择以下其中一项:

alert替换为alternative-alert-class-name

$1alternative-alert-class-name$2

或者不用替换alert

$1$2

PHP代码(注意使用不区分大小写):

$result = preg_replace('/(<[A-Z][A-Z0-9]*\b[^>]*\bclass\s*=\s*"(?:|[^"]+))\balert\b((?:|[^"]+)")/imx', '$1alternative-alert-class-name$2', $subject);

示例输入:

<div class="alert">Alert alert</div>
<div class="alert solid">Alert alert</div>
<div class = "alert solid">Alert alert</div>
<div class=" big alert solid">Alert alert</div>
<div class = " big alert solid">Alert alert</div>
<div something="xx" class = " big alert solid">Alert alert</div>
<span enabled something="xx" class = " big alert solid">Alert alert</span>
<div class=" big solid">Alert alert</div>

示例输出:

<div class="alternative-alert-class-name">Alert alert</div>
<div class="alternative-alert-class-name solid">Alert alert</div>
<div class = "alternative-alert-class-name solid">Alert alert</div>
<div class=" big alternative-alert-class-name solid">Alert alert</div>
<div class = " big alternative-alert-class-name solid">Alert alert</div>
<div something="xx" class = " big alternative-alert-class-name solid">Alert alert</div>
<span enabled something="xx" class = " big alternative-alert-class-name solid">Alert alert</span>
<div class=" big solid">Alert alert</div>

答案 2 :(得分:0)

您可以使用:

$data = <<<EOD
<div class=" big alert solid">Alert alert</div>
<div class = "other-alert-class solid">Alert alert</div>
<div class=" big solid">Alert alert</div>
<div class=' big alert solid'>Alert alert</div>
<div class  =  alert>Alert alert</div>
EOD;

$pattern = '~\sclass\s*=\s*(?>["\'](?>[^"\'a]++|(?<=\B|-)a|a(?!lert\b[^-]))*)?\Kalert\b~';

$result = preg_replace($pattern, 'otherclass', $data);