2013-10-25 80 views
0

我很弱,正则表达式,需要帮助。我的问题是我必须提取所有匹配给定模式的字符串,我已经成为一个数组。请参见下面的问题:PHP字符串提取

字符串

<?php 
$alert_types = array(
    'warning' => array('', __l("Warning!")), 
    'error' => array('alert-error', __l("Error!")), 
    'success' => array('alert-success', __l("Success!")), 
    'info' => array('alert-info', __l("For your information.")), 
);?> 

该守则的preg_match

preg_match("/.*[_][_][l][\(]['\"](.*)['\"][\)].*/", $content, $matches); 

我只获得了第一个比赛是警告!。我期待的比赛将具有以下值:

Warning!, Error!, Success!, For your information. 

其实我使用的file_get_contents($文件)来获得字符串。

任何人都可以帮助我解决这个问题。先谢谢你。

+0

抱歉,我应该使用preg_match_all而不是preg_match – lukaserat

+0

@mario是的,你说得对。我也解决了这个问题,但没有考虑可能的重复。 :)这是我的正则表达式:preg_match_all(“| __l \(['\”](。*)['\“] \)|”,$ content,$ matches,PREG_PATTERN_ORDER);对那些感兴趣的人。 – lukaserat

回答

2

preg_match()仅查找字符串中的第一个匹配项。使用preg_match_all()获取所有匹配项。

preg_match_all("/.*__l\(['\"](.*?)['\"]\).*/", $content, $matches); 

$matches[1]将包含您正在查找的字符串数组。

顺便说一句,你不需要所有的单字符括号。只需将该字符放入正则表达式即可。

var_dump($matches); 

array(2) { 
    [0]=> 
    array(4) { 
    [0]=> 
    string(45) " 'warning' => array('', __l("Warning!"))," 
    [1]=> 
    string(52) " 'error' => array('alert-error', __l("Error!"))," 
    [2]=> 
    string(58) " 'success' => array('alert-success', __l("Success!"))," 
    [3]=> 
    string(65) " 'info' => array('alert-info', __l("For your information."))," 
    } 
    [1]=> 
    array(4) { 
    [0]=> 
    string(8) "Warning!" 
    [1]=> 
    string(6) "Error!" 
    [2]=> 
    string(8) "Success!" 
    [3]=> 
    string(21) "For your information." 
    } 
} 
+0

谢谢Barmar,我已经这样做了,但是又出现了一些问题。我有这样一个字符串:'sprintf(__ l('你现在有%d的车,希望%sview%s?'),$ totalPrintCart,“","”),输出结果是'You have%d on现在购物车。 “%sview%s?'),$ totalPrintCart,\” \“,\”<\/a>'。你知道如何得到吗?你现在有%d! ' – lukaserat

+0

我已经将'(。*)'换成'(。*?)'使它非贪婪 – Barmar

+0

它起作用!:)谢谢! – lukaserat