文章浏览 复制本页面地址

PHP正则表达式加函数匹配中文汉子

今天一个朋友说要写个正则表达式,需求是这样的

他要实现    根据IP抓归属地    例如:  山东省   则 显示山东    如果是 山东省临沂市  则显示市前面的 山东省临沂。

我想了想 代码如下;

方法一、

<?php
 /*
 * @Desc   :get province and city by string
 * @Author : Brave
 * @Date   : 2013-5-28 22:26:15
 */
 function get_pro_city($temp,$str){
  $reg = "/^(.*?)$temp/su";
  preg_match($reg, $str, $matches);
  return $matches[1];
 }

 echo get_pro_city(省,'山东省临沂市');

echo get_pro_city(市,'山东省临沂市');

?>

方法二、

<?php
 /*
 * @Desc   :get province and city by string
 * @Author : Brave
 * @Date   : 2013-5-28 22:26:15
 */
 function get_pro_city($temp,$str){
  $reg = "/^(.*?)$temp/su";
  preg_match_all($reg, $str, $matches, PREG_SET_ORDER);
  return $matches[1];
 }

 echo get_pro_city(省,'山东省临沂市');

echo get_pro_city(市,'山东省临沂市');

?>

标签:
上一篇:
下一篇: