正则表达式PHP尝试剖析字符串

时间:2014-05-10 15:29:18

标签: php regex

以下是我的字符串示例:

$string = 'Vivamus non risus non diam {some-text-here} varius sollicitudin in non dui. Phasellus egestas {some-more-text-here} quis augue eu pharetra. Curabitur rutrum non lectus et aliquam. Fusce quis rutrum magna. Sed at tristique dui, scelerisque tincidunt tortor. Integer a nibh gravida urna pulvinar vehicula. Curabitur ut felis ut mi imperdiet condimentum {and-some-goes-here-too}. Vestibulum sit amet {of-course-here-as-well} diam mi. Quisque diam dui, convallis dapibus suscipit sit amet, auctor in turpis.';

如果您注意到{these-things-with-text-in-them}中有$string个问题。我使用此函数将它们从$string中拉出来。

preg_match_all('/\{(.*?)\}/', $string, $bracket_data);
print '<pre>'; print_r($bracket_data[1]); print '</pre>';

将吐出这个:

Array
(
    [0] => some-text-here
    [1] => some-more-text-here
    [2] => and-some-goes-here-too
    [3] => of-course-here-as-well
)

这很好地解决了这个问题。我想要的是相同的结果,但$string的部分在括号内,仍然使用preg_match_all()。因此,在本例中使用$string作为示例,所需的结果将是:

Array
(
    [0] => Vivamus non risus non diam 
    [1] =>  varius sollicitudin in non dui. Phasellus egestas 
    [2] =>  quis augue eu pharetra. Curabitur rutrum non lectus et aliquam. Fusce quis rutrum magna. Sed at tristique dui, scelerisque tincidunt tortor. Integer a nibh gravida urna pulvinar vehicula. Curabitur ut felis ut mi imperdiet condimentum 
    [3] => . Vestibulum sit amet 
    [4] =>  diam mi. Quisque diam dui, convallis dapibus suscipit sit amet, auctor in turpis.
)

有没有人对我现有的正则表达式有任何建议或批评?

注意:括号内的文字可以在任何安排中找到。他们可以在开始时,肩并肩,最后和任何数量。括号内的文字相同

2 个答案:

答案 0 :(得分:6)

preg_split()使用相同的正则表达式。我还在正则表达式周围添加\s*以从匹配项中排除空格。

$arr = preg_split('/\s*\{(.*?)\}\s*/', $string);

输出:

Array
(
    [0] => Vivamus non risus non diam
    [1] => varius sollicitudin in non dui. Phasellus egestas
    [2] => quis augue eu pharetra. Curabitur rutrum non lectus et aliquam. Fusce quis rutrum magna. Sed at tristique dui, scelerisque tincidunt tortor. Integer a nibh gravida urna pulvinar vehicula. Curabitur ut felis ut mi imperdiet condimentum
    [3] => . Vestibulum sit amet
    [4] => diam mi. Quisque diam dui, convallis dapibus suscipit sit amet, auctor in turpis.
)

Demo

答案 1 :(得分:2)

preg_split(如Amal建议的那样)可以工作,但是如果你想要一个数组中的所有内容,以下正则表达式将会有所帮助。它将包括{..}之前,之内和之后的文字:

/(.*?)\{(.*?)\}([^{]*)/

http://regex101.com/r/wS4iJ1