PCRE正则表达式函数:
preg_match()和preg_match_all() preg_quote() preg_split() preg_grep() preg_replace() |
函数的具体使用,我们可以通过PHP手册来找到,下面分享一些平时积累的正则表达式:
匹配action属性
$str = ‘‘; $match = ‘‘; preg_match_all(‘/\s+action=\"(?!http:)(.*?)\"\s/‘, $str, $match); print_r($match); |
在正则中使用回调函数
/** * replace some string by callback function * */ function callback_replace() { $url = ‘http://esfang.house.sina.com.cn‘; $str = ‘‘; $str = preg_replace ( ‘/(?<=\saction=\")(?!http:)(.*?)(?=\"\s)/e‘, ‘search(\$url, \\1)‘, $str ); echo $str; } function search($url, $match){ return $url . ‘/‘ . $match; } |
带断言的正则匹配
$match = ‘‘; $str = ‘xxxxxx.com.cn bold font paragraph text ‘; preg_match_all ( ‘/(?<=<(\w{1})>).*(?=<\/\1>)/‘, $str, $match ); echo "匹配没有属性的HTML标签中的内容:"; print_r ( $match ); |
替换HTML源码中的地址
$form_html = preg_replace ( ‘/(?<=\saction=\"|\ssrc=\"|\shref=\")(?!http:|javascript)(.*?)(?=\"\s)/e‘, ‘add_url(\$url, \‘\\1\‘)‘, $form_html ); |
最后,正则工具虽然强大,但是从效率和编写时间上来讲,有的时候可能没有explode来的更直接,对于一些紧急或者要求不高的任务,简单、粗暴的方法也许更好。
而对于preg和ereg两个系列之间的执行效率,曾看到文章说preg要更快一点,具体由于使用ereg的时候并不多,而且也要推出历史舞台了,再加个个人更偏好于PCRE的方式,所以笔者就不做比较了,熟悉的朋友可以发表下意见,谢谢。
.分页: [1] [2]
TAG: PHP 正则表达式