D
D
Dmitry Prikhodchenko2013-11-18 09:00:26
PHP
Dmitry Prikhodchenko, 2013-11-18 09:00:26

How to pass all elements of a subpattern in a regular expression?

Hello, I have a regular expression:

$content = preg_replace_callback('/{([a-z]{1,9})(\s[a-z]{1,9}){0,9}}/', 'function123', $content);
This regular expression should process such strings as {name parameter parameter....} The
question is how to make preg_replace pass not only the last occurrence of the subpattern, but all elements. Example: {title abc zxc qwe}, preg_replace_callback, will return the entire string, + title and qwe

Answer the question

In order to leave comments, you need to log in

4 answer(s)
B
bahek2462774, 2013-11-18
@bahek2462774

if you need to get ['title' , 'abc' , 'zxc' , 'qwe'] - then you can just
/[az]{1,9}/

A
Alexander, 2013-11-18
@DrunkenMaster

I would do something like this:

$content = '{title abc zxc qwe} test {title abc zxc qwe} {title}';

function matches($matches) {
    $title = $matches['title'];
    $params = isset($matches['params']) ? preg_split('/\s/', $matches['params']) : array();
    var_dump($title);
    var_dump($params);
}

$content = preg_replace_callback('/\{(?P<title>[a-z]{1,9})(?:\s(?P<params>[^}]+))?\}/', 'matches', $content);

print $content;

B
bahek2462774, 2013-11-18
@bahek2462774

something like this

$content = preg_replace_callback('/(?:{)([a-z]{1,9})\s([a-z]{1,9})\s([a-z]{1,9})\s([a-z]{1,9})/', function($a) {
    var_dump($a);
}, '{title abc zxc qwe}');

but unfortunately I don't know how to do it with an unknown number of parameters.
and why it is impossible to pull out each parameter one by one in the callback function?

B
bahek2462774, 2013-11-18
@bahek2462774

and preg_match_all will not save the situation?

preg_match_all('/[a-z]{1,9}/','{title abc zxc qwe}',  $matches);
var_dump($matches);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question