2012-08-15 53 views
-1

提供的句子我有一个文本格式在我的数据库为:的preg_match得到的格式

Name : John Thompson 
Address : 123 street abc state xyz country 

如何获得价值名称即:通过的preg_match约翰·汤普森? 我试图避免长时间的爆炸过程,因为除了名字和地址外,我还会得到其他的东西。

我需要有一个简单的正则表达式,可以让我得到一个字符串包含句子的名称:,地址:等等。

回答

0

简单地说:

$matches = array(); 
preg_match_all('/^(?P<propname>[^:]+):\s*(?P<propval>.*)$/m', $string, $matches, PREG_SET_ORDER); 
print_r($matches); 

此正则表达式的冒号之前匹配任何东西,抓住它propname,其余的行年底将在propval被捕获。 产生的结构将

Array 
(
    [0] => Array 
     (
      [0] => Name : John Thompson 
      [propname] => Name 
      [1] => Name 
      [propval] => John Thompson 
      [2] => John Thompson 
     ) 

    [1] => Array 
     (
      [0] => Address : 123 street abc state xyz country 
      [propname] => Address 
      [1] => Address 
      [propval] => 123 street abc state xyz country 
      [2] => 123 street abc state xyz country 
     ) 
) 

由于这是一个简单的正则表达式,我认为,你不熟悉正则表达式,所以我强烈建议阅读J.F. Friedl - Mastering Regular expressions,你很快就会易工艺完美演绎:-)