问题描述:

Here is an example of my string:

$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.';

If you notice there are {these-things-with-text-in-them} peppered throughout the $string. I use this function to pull them out of the $string.

preg_match_all('/\{(.*?)\}/', $string, $bracket_data);

print '<pre>'; print_r($bracket_data[1]); print '</pre>';

Which will spit out this:

Array

(

[0] => some-text-here

[1] => some-more-text-here

[2] => and-some-goes-here-too

[3] => of-course-here-as-well

)

That does the trick nicely. What I'd like to have is the same result, but with the parts of the $string that are not within brackets, still using preg_match_all(). So in this case using $string as an example, the desired result would be:

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.

)

Does anyone have any suggestions, or critique for the existing regex I have?

NOTE: The text within the brackets can be found in any arrangement. They can be at the beginning, shoulder-to-shoulder, at the end, and any amount. Same for the text outside of the brackets

网友答案:

Use the same regex with preg_split(). I've also added \s* around the regex to exclude whitespace from the matches.

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

Output:

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

网友答案:

The preg_split (as Amal suggested) would work, but if you want everything in one array, the following regex will be helpful. It will include the text before, within and after the {..}:

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

http://regex101.com/r/wS4iJ1

相关阅读:
Top