-1

I would like to extract the following string <%MYSTRING123%> from the example string below

'sdfsdf sdfsdf fd<%MYSTRING123%>d12df fsdsgsg d'

I found this exact question has been asked already, so i tried their solution as below:

$input = 'sdfsdf sdfsdf fd<%MYSTRING123%>d12df fsdsgsg d';
preg_match_all('/\[<%MYSTRING\](.*?)\[%>\]/', $input, $matches);
var_dump($matches);

Output

array(2) {
  [0]=>
  array(0) {
  }
  [1]=>
  array(0) {
  }
}

Expected Output

array(1) {
  [0]=> '<%MYSTRING123%>'
}

Link to PHP example

Community
  • 1
  • 1
steve
  • 471
  • 6
  • 15

2 Answers2

1

Since you are using preg_match_all() you will always get a 2-dimensional array. This will at least give you the content you are looking for:

/<%MYSTRING\d+%>/

https://regex101.com/r/abVAkC/1

http://ideone.com/I8VRoV

PS: the \[ and \] in the topic you linked are part of their input ('BBCode'-tags). So these do not apply for your input.

Doqnach
  • 372
  • 1
  • 8
0

Looking to your regex, it seems you need to be able to get <%MYSTRING-anynumber%>, right?

Try to change a bit your regex the following:

<?php
$input = 'sdfsdf sdfsdf fd<%MYSTRING123%>d12df fsdsgsg d';
preg_match_all('/\<%MYSTRING.*?%>/', $input, $matches);
var_dump($matches);

Demo

Mistalis
  • 17,793
  • 13
  • 73
  • 97