Eli
Eli

Reputation: 4359

php how to do a preg_match() for a word that follows another word

As an example I'll use this line:

/*! jQuery v1.7.1 jquery.com | jquery.org/license */

how would I use preg_match to find and isolate into a $version variable the 1.7.1?

Taking into account that the version number in that string will change dynamically without notice.

so in plain English it would sound like:

find the term 'jQuery v' and grab the following characters up until a space is found

Upvotes: 1

Views: 437

Answers (3)

dfsq
dfsq

Reputation: 193261

preg_match('|jQuery v([^\s]+)|', $str, $m);
$version = $m[1];

Upvotes: 0

codaddict
codaddict

Reputation: 455052

$str = '/*! jQuery v1.7.1 jquery.com | jquery.org/license */';
if(preg_match('/jQuery v(\S+)/', $str, $m)) {
        $ver = $m[1];
}

Upvotes: 1

André Laszlo
André Laszlo

Reputation: 15537

Here's an interactive php session for you:

php > $haystack = "/*! jQuery v1.7.1 jquery.com | jquery.org/license */";
php > preg_match('/jQuery v([^ ]*)/', $haystack, $matches);
php > print_r($matches);
Array
(
    [0] => jQuery v1.7.1
    [1] => 1.7.1
)

As you can see, the first match group contains your version number.

Upvotes: 1

Related Questions