Dani-Br
Dani-Br

Reputation: 2457

PHP: Howto get sub_strings by regexp

I have htacess rule like this:

RewriteRule ^([A-z])([0-9]+)-([^/]*)?$ index.php?tt=$1&ii=$2&ll=$3

Is there any PHP function that can do the same ?
Something like:

$A = XXXX_preg_match("([A-z])([0-9]+)-([^/]*)" , "A123-boooooo");
// $A become to =array("A","123","boooooo")

Upvotes: 0

Views: 54

Answers (3)

Carlos
Carlos

Reputation: 5072

preg_match('/([a-zA-Z])(\d+)-([^\/]+)/', 'A123-boooooo', $A);
array_shift($A);

Output: print_r($A);

Array
(
    [0] => A
    [1] => 123
    [2] => boooooo
)

Upvotes: 1

Martin Ender
Martin Ender

Reputation: 44259

If you just want to retrieve those three values, you can pass an out-parameter to preg_match like this:

preg_match(
    '~^([A-z])([0-9]+)-([^/]*)$~' ,
    'A123-boooooo',
    $matches
);

$fullMatch = $matches[0]; // 'A123-boooooo'
$letter = $matches[1];    // 'A'
$number = $matches[2];    // '123'
$word = $matches[3];      // 'boooooo'

// Therefore
$A = array_slice($matches, 1);

If you want to do the replacement right away, use preg_replace:

$newString = preg_replace(
    '~^([A-z])([0-9]+)-([^/]*)$~',
    'index.php?tt=$1&ii=$2&ll=$3',
    'A123-boooooo
);

The documentation of these is usually really good for further information.

Upvotes: 1

Toto
Toto

Reputation: 91430

According to preg_match doc

preg_match("~([A-z])([0-9]+)-([^/]*)~" , "A123-boooooo", $matches);
print_r($matches);

output:

Array
(
    [0] => A123-boooooo
    [1] => A
    [2] => 123
    [3] => boooooo
)

Upvotes: 0

Related Questions