Newmania
Newmania

Reputation: 662

PHP pattern match to identify a specific string with a number in

I am putting "merge" fields in my text, ie:

::sub_menu::33::

I want to be able to find all occurrences of this pattern:

::sub_menu::(any number)::

Then I'll go on to extract the number and replace it (I don't need help with that bit thanks).

I've used preg_match_all before, but am not sure how to use it when I want to use a specific string as part of the match? Any help much apprciated.

Upvotes: 1

Views: 92

Answers (3)

zriel
zriel

Reputation: 79

You can try this one:

$input = '::sub_menu::33::';

/* if you have one or more numbers,  use (+) quantifiers*/ 
if ( preg_match('/::sub_menu::[0-9]+::/', $input, $match) )


/* if you want to put min/max quantifiers min by 2 and max by 10*/
if ( preg_match('/::sub_menu::[0-9]{2,10}::/', $input, $match) ){

    print_r($match);

}

Upvotes: 0

anubhava
anubhava

Reputation: 786349

I want to be able to find all occurrences of this pattern: ::sub_menu::(any number)::

You can use this regex:

/::sub_menu::\(\d+\)::/

To use it in preg_match_all use:

if ( preg_match_all('/::sub_menu::\((\d+)\)::/', $input, $match) )
    print_r($match[0]);

Upvotes: 1

Mark Lowe
Mark Lowe

Reputation: 1076

You can use:

preg_match("/::sub_menu::\((\d+)\)::/", $input_line, $output_array);

The $output_array for an input of ::sub_menu::(33):: will contain:

Array
(
    [0] => ::sub_menu::(33)::
    [1] => 33
)

Upvotes: 0

Related Questions