John Davidson

php - how i can explode (split) a gived string for text and separator?

0 comments
Message:


how i can parse a string formed from two block:



  1. { text }

  2. text


I have two regex for both situazion:



  1. \{[^\}]+\}

  2. *.


But not understood with combine it in one regex. I have thinked to use or ( | ) operator doing so:


/(\{[^\}]+\}|.*)/

But it don't work. How i can solve it?


In concrete, if i have a string as:


"{this is first text} this is second text {this is third text}"

using preg_match_all i want to have somthing as:


Array
(
[0] => Array
(
[0] => {this is first text}
[1] => this is second text
[2] => {this is third text}
)

)

But i have as result:


Array
(
[0] => Array
(
[0] => {this is first text}
[1] => this is second text {this is third text}
[2] =>
)

)

Thanks very much for help.



My Answer:
You can achieve the desired result by using the following regex pattern:

php
$pattern = '/\{[^\}]+\}|[^{]+/';
$string = "{this is first text} this is second text {this is third text}";

preg_match_all($pattern, $string, $matches);

print_r($matches[0]);


This will output:


Array
(
[0] => {this is first text}
[1] => this is second text
[2] => {this is third text}
)


This pattern will match either text enclosed in curly braces or text that is not enclosed in curly braces, effectively splitting the string based on the specified separator.

Rate this post

4 of 5 based on 4931 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us