preg_match or similar to get value from a string
I am not good with preg_match
or similar functions which are not deprecated.
Here are 2 strings:
/Cluster-Computers-c-10.html
/Mega-Clusters-c-15_32.html
I would to find out:
In number 1 example, how to get the value betwee开发者_Go百科n -c-
and .html
(the value in the example is 10). The value is always an integer (numeric)
In number 2 example, how to get the value between -c-
and .html
(the value in the example is 15_32
) . The value is always an integer seperated by _
Basically what I want to do is check if a string has either c-10.html
or c-15_32.html
and get the value and pass it to the database.
You can do:
preg_match('/-c-(\d+(?:_\d+)?)\.html$/i',$str);
Explanation:
-c- : A literal -c-
( : Beginning of capturing group
\d+ : one or more digits, that is a number
(?: : Beginning of a non-capturing group
_\d+ : _ followed by a number
) : End of non-capturing group
? : Makes the last group optional
) : End of capturing group
\. : . is a metacharacter to match any char (expect newline) to match
a literal . you need to escape it.
html : a literal html
$ : End anchor. Without it the above pattern will match any part
of the input string not just the end.
See it
preg_match('~-c-(.*?)\.html$~', $str, $matches)
var_dump($matches);
/-c-(\d+(?:_\d+)?)\.html$/i
-c-
look for -c-
(\d+(?:_\d+)?)
match number or number-underscore-number
\.html
a period and trailing html
$
force it to match the end of the line
i
case-insensitive match
Example:
<?php
header('Content-Type: text/plain');
$t = Array(
'1) /Cluster-Computers-c-10.html',
'2) /Mega-Clusters-c-15_32.html'
);
foreach ($t as $test){
$_ = null;
if (preg_match('/-c-(\d+(?:_\d+)?)\.html$/i',$test,$_))
var_dump($_);
echo "\r\n";
}
?>
output:
array(2) {
[0]=>
string(10) "-c-10.html"
[1]=>
string(2) "10"
}
array(2) {
[0]=>
string(13) "-c-15_32.html"
[1]=>
string(5) "15_32"
}
Working Code: http://www.ideone.com/B70AQ
The simplest way I see would be:
preg_match( '/-c-([^.]+)\.html/i', $url, $matches );
var_dump( $matches );
精彩评论