2011-07-22 9 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

正しいアプローチを使用することであろう【のDOMDocument(http://www.php.net/manual/en/class.domdocument.php)(HTMLパーサ)疫病のような正規表現を避けてください。 –

+0

ここで私の問題を読んでください。http:// stackoverflow.com/question/6793224/dom-parser-remove-certain-attributes-only'。ありがとう。 – laukok

+0

'style'属性にアクセスして解析するアドバイスに耳を傾けたくないのですか?これは、HTML上でregexを使うよりはるかに優れたアプローチです。 –

答えて

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:それは逆転しました。 –