Home >Backend Development >PHP Tutorial > 一个正则表达式的写法,该如何解决

一个正则表达式的写法,该如何解决

WBOY
WBOYOriginal
2016-06-13 13:48:23910browse

一个正则表达式的写法
$str='[movie=http://a.com/a.X]'; //X格式为除了.mp3和.wmv以外的任何字符串
$ptn="/\[movie\=.*\.[^(mp3|wmv)]\]/i";
$str=preg_replace($ptn,'x',$str);
echo $str;
怎么不对啊

------解决方案--------------------
你没有理解正则里中括号[]的含义,[]里所有的东西匹配的时候只“消耗”单个字符。
除xxx之外的需求一般用“否定前瞻”(negative lookahead) 来实现。
------解决方案--------------------
$str='[movie=http://a.com/a.mp3]';
$ptn="/\[movie\=.*\.[^(mp3|wmv)]+\]/i"; 

if(preg_match($ptn,$str)) {
echo 'Y';
} else {
echo 'N';
}
------解决方案--------------------

PHP code
<?php $str='[movie=http://a.com/a.mp3]';           //X格式为除了.mp3和.wmv以外的任何字符串
$ptn="/\[movie\=.*(?<!mp3|wmv)]$/";
$str=preg_replace($ptn,'x',$str);
echo   $str; 
?>
<br><font color="#e78608">------解决方案--------------------</font><br>
PHP code
<?php $str='[movie=http://a.com/a.mp3]';
//$str='[movie=http://a.com/a.mp]';
$ptn="/\[movie\=(?>.*\.)(?:(?!mp3|wmv).+)\]/";

if(preg_match($ptn,$str,$g))   {
 echo   'Y';
 print_r($g);
}   else   {
 echo   'N';
}
?> <div class="clear">
                 
              
              
        
            </div>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn