Kirill Firsov
Kirill Firsov

Reputation: 519

php regexp to variable

How I can write regexp to variable in regular expression?

$string = 'Test regular expression';
preg_match('#test (^\s+) expression#is', $string, $b);

//$b[1] = 'regular'; // But I need another way. 

I want to get

$b['string'] = 'regular'; // Not using $b['string'] = $b[1];

Maybe

$regex = '#test (^\s+)/string/ expression#is';

Maybe there's a way to write a regular expression into an array variable in the regular expression?

Thank you, I hope you understand me.

Upvotes: 1

Views: 1267

Answers (1)

qbert220
qbert220

Reputation: 11556

You can do this with named capturing expressions:

preg_match('#test (?P<string>[^\s]+) expression#is', $string, $b);
print_r($b);

Upvotes: 1

Related Questions