删除这两个标记之间的问号

时间:2010-11-08 18:31:49

标签: php regex

例如,我有这个字符串:

asd? asdfasdfsdf <description>&lt;div? style=&quot;color:000000;font-family:Arial, Helvetica, ?sans-serif;font-size:12px;font-size:12px;width:555px;&quot;&gt;Bohus Malm?t;/a&gt;</description> blah blah blah? asdfasfize:12px;font-size:?

我需要知道如何删除所有?仅存在于开始和结束“description”标签之间,但不存在于其外部。

谢谢!

3 个答案:

答案 0 :(得分:1)

$str = 'asd? asdfasdfsdf <description>&lt;div? style=&quot;color:000000;font-' . 
       'family:Arial, Helvetica, ?sans-serif;font-size:12px;font-size:12px;' . 
       'width:555px;&quot;&gt;Bohus Malm?t;/a&gt;</description> blah blah ' . 
       'blah? asdfasfize:12px;font-size:?';  
function myReplace($matches)  
{  
    return $matches[1].str_replace('?', '', $matches[2]).$matches[3];  
}  
$result = preg_replace_callback(
    '|(.*<description>)(.*)(<\/description>.*)|', 
    'myReplace', 
    $str
);  
echo htmlspecialchars($result);  

答案 1 :(得分:0)

怎么样:

$var = 'asd? asdfasdfsdf <description>&lt;div? style=&quot;color:000000;font-family:Arial, Helvetica, ?sans-serif;font-size:12px;font-size:12px;width:555px;&quot;&gt;Bohus Malm?t;/a&gt;</description> blah blah blah? asdfasfize:12px;font-size:?';
preg_match( '/(.*)(<description>.*<\/description>)(.*)/', $var, $matches );
$new = $matches[1] . str_replace( '?', '', $matches[2] ) . $matches[3];

答案 2 :(得分:0)

<?php
$string = 'asd? asdfasdfsdf <description>&lt;div? style=&quot;color:000000;font-family:Arial, Helvetica, ?sans-serif;font-size:12px;font-size:12px;width:555px;&quot;&gt;Bohus Malm?t;/a&gt;</description> blah blah blah? asdfasfize:12px;font-size:?';
$regex = '/(<description>.*)\?(.*<\/description>)/i';

while (preg_match($regex, $string)) {
     $string = preg_replace($regex, '$1$2', $string);
}
echo $string; 
?>