Jeram
Jeram

Reputation: 15

I need preg_match_all() pattern in getting string inside square bracket tags PHP

I want to parse a string to get the value inside a square bracket tag:

[vc_column_text][/vc_column_text]

I am using preg_match_all() in PHP

$string = '[vc_row][vc_column][/vc_column][/vc_row][vc_row][vc_column width="1/2"][vc_column_text css=".vc_custom_1576642149231{margin-bottom: 0px !important;}"]This is the string I want to fetch[/vc_column_text][/vc_column][/vc_row]`;

I tried this:

preg_match_all("'[vc_column_text(.*?)](.*?)[/vc_column_text]'", $string, $matches);

But this only returns an array of 2-3 characters:

enter image description here

A help will be very much appreciated :)

Upvotes: 0

Views: 206

Answers (1)

The fourth bird
The fourth bird

Reputation: 163632

If you want to match only the sentence, you could use first match [vc_column_text followed by any char except [ or ] and then match the closing ]

Then match 0+ occurrences of a whitespace char and capture 1 or more occurrences of any char except a whitespace in group 1.

\[vc_column_text[^][]*\]\s*(.+?)\[/vc_column_text]

Explanation

  • \[vc_column_text Match [vc_column_text
  • [^][]*\] Match [, then 0+ occurrences of any char except [ or ] and match ]
  • \s* Match 0+ whitespace chars
  • (.+?) Capture group 1, match any char 1+ times non greedy
  • \[/vc_column_text] Match [/vc_column_text]

Regex demo | Php demo

Example code

$string = '[vc_row][vc_column][/vc_column][/vc_row][vc_row][vc_column width="1/2"][vc_column_text css=".vc_custom_1576642149231{margin-bottom: 0px !important;}"]This is the string I want to fetch[/vc_column_text][/vc_column][/vc_row]';
preg_match_all("~\[vc_column_text[^][]*\]\s*(.+?)\[/vc_column_text]~", $string, $matches);
print_r($matches[1]);

Output

Array
(
    [0] => This is the string I want to fetch
)

Upvotes: 1

Related Questions