1

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.

1 Answer 1

1

You can do this with named capturing expressions:

preg_match('#test (?P<string>[^\s]+) expression#is', $string, $b);
print_r($b);
Sign up to request clarification or add additional context in comments.

1 Comment

Edit: Added missing [] round the ^\s

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.