bestprogrammerintheworld
bestprogrammerintheworld

Reputation: 5520

Extract ids (values) with regex?

I have a text

[wow id="44"] bla bla bla [wow id="99"] bla bla bla [wow id="100"] bla

How do I get the values 44, 99, and 100 in a smart way? Is regex "the way to go" ?

Upvotes: 0

Views: 99

Answers (4)

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

php:

 $re = "/\\[[\\w\\s]*id=\"(\\d+)/m";
    $str = " down vote favorite\n    \n\nI have a text\nid=\"44\"\n[wow id=\"44\"] bla bla bla [wow id=\"99\"] bla bla bla [wow id=\"100\"] bla";

    preg_match_all($re, $str, $matches);

See live

Upvotes: 1

Rakesh Sharma
Rakesh Sharma

Reputation: 13728

try with preg_match_all()

$str = '[wow id="44"] bla bla bla [wow id="99"] bla bla bla [wow id="100"] bla';
preg_match_all('/[1-9][0-9]*/', $str, $m);
print_r($m);//Array ( [0] => Array ( [0] => 44 [1] => 99 [2] => 100 ) ) 

For more :- Regex pattern for numeric values

Upvotes: 2

Arnab Nandy
Arnab Nandy

Reputation: 6692

This may help you

preg_match_all("/\b(\d{6,20})\b/", $input_lines, $output_array);

Here is the result.

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

Use \K to discard the previously matched characters from printing in the final output.

\[wow id="\K[^"]*(?="])

Code:

preg_match_all('~\[wow id="\K[^"]*(?="])~', $str, $match);

OR

Use capturing groups.

\[wow id="([^"]*)"]

Upvotes: 3

Related Questions