2011-07-22 35 views
0

下面的正則表達式有什麼問題?正則表達式:匹配或替換它

$content = ' 
<span style="text-decoration: underline;">cultural</span> 
<span style="text-decoration: line-through;">heart</span> 
<span style="font-family: " lang="EN-US">May</span> 
'; 

$regex = '/<span style=\"text\-decoration\: underline\;\">(.*?)<\/span>/is'; 
if (!preg_match($regex,$content)) 
{ 

    $content = preg_replace("/<span.*?\>(.*?)<\/span>/is", "$1", $content); 
} 

我想要做的是去除所有跨度除了跨度要麼,

style="text-decoration: underline;

style="text-decoration: line-through; 

我怎樣才能解決呢?

+0

正確的做法是使用一個[DOM文檔](http://www.php.net/manual/en/class.domdocument.php)(HTML解析器)並避免像瘟疫一樣的正則表達式。 –

+0

請在這裏閱讀我的問題'http:// stackoverflow.com/questions/6793224/dom-parser-remove-certain-attributes-only'。謝謝。 – laukok

+0

所以你不想聽取建議來訪問'style'屬性並解析它?這比在HTML上使用正則表達式要好得多。 –

回答

1

DOM方法:

<?php 
    $content = '<span style="text-decoration: underline;">cultural</span>' 
      . '<span style="text-decoration: line-through;">heart</span>' 
      . '<span style="font-family: " lang="EN-US">May</span>'; 

    $dom = new DOMDocument(); 
    $dom->loadHTML($content); 

    // grab every span, then iterate over it. Because we may be removing 
    // spans, we reference the ->length property off the DOMNode and use an 
    // iterator ($s) 
    $spans = $dom->getElementsByTagName('span'); 
    for ($s = 0; $s < $spans->length; $s++) 
    { 
    // grab the current span element 
    $span = $spans->item($s); 

    // iterate over the attributes looking for style tags 
    $attributes = $span->attributes->length; 
    for ($a = 0; $a < $attributes; $a++) 
    { 
     // grab the attribute, check if it's a style tag. 
     // if is is, also check if it has the text-decoration applied 
     $attribute = $span->attributes->item($a); 
     if ($attribute->name == 'style' && !preg_match('/text-decoration:\s*(?:underline|line-through);/i', $attribute->value)) 
     { 
     // found it. Now, referencing its parent, we want to move all the children 
     // up the tree, then remove the span itself from the tree. 
     $parent = $span->parentNode; 
     foreach ($span->childNodes as $child) 
     { 
      $parent->insertBefore($child->cloneNode(), $span); 
     } 
     $parent->removeChild($span); 

     // decrement the iterator so we don't end up skipping over nodes 
     $s--; 
     } 
    } 
    } 
+0

謝謝!但它應該使用'!preg_match()':-) – laukok

+0

@lauthiamkok:哎呀,把它顛倒過來。 –