抱歉我的英语不好。我有一个问题,我想比较两个不同的字符串使用reg exp。第一个字符串的结构类似于 a-b-1 ,例如:mobile-phone-1。第二个字符串的结构类似于 a-b-1 / d-e-2 ,例如:mobile-phone-1 / nokia-asha-23。我该怎么做?你可以使用preg_match()方法或者某种方法...这个方法适用于两个不同的字符串。非常感谢!
代码演示:
if (preg_match("reg exp 1", string1)) { // do something }
if (preg_match("reg exp 2", string2)) { // do something }
P / S:不应过多关注代码演示
答案 0 :(得分:1)
$pattern = '#[\w]+-[\w]+-[\d]+(/[\w]+-[\w]+-[\d]+)?#';
if (preg_match($pattern, $str, $matches)){
return $matches;
}
要匹配较短的字符串,请使用:
$pattern = '#[\w]+-[\w]+-[\d]+#';
要匹配更长的时间:
$pattern = '#[\w]+-[\w]+-[\d]+/[\w]+-[\w]+-[\d]+#';
将更长的符号与更长的短划线相匹配:
$pattern = '#[\w]+-[\w]+-[\d]+/[\w-]+[\d]+#';
答案 1 :(得分:1)
if(preg_match("/^([a-z]+)-([a-z]+)-([0-9]+)$/i",$string1))
if(preg_match("/^([a-z]+)-([a-z]+)-([0-9]+)\/([a-z]+)-([a-z]+)-([0-9]+)$/i",$string2))
'我'到底是为了区分大小写。
答案 2 :(得分:1)
正则表达式及解释。一步一步解决。
$text1='mobile is for you--phone-341/nokia-asha-253'; //sample string 1
$text2='mobile-phone-341'; //sample string 2
$regular_expression1='(\w)'; // Word (mobile)
$regular_expression2='(-)'; // Any Single Character (-)
$regular_expression3='(\w)'; // Word (phone)
$regular_expression4='(-)'; // Any Single Character (-)
$regular_expression5='(\d+)'; // Integer Number (341)
$regular_expression6='(\/)'; // Any Single Character (/)
$regular_expression7='(\w)'; // Word (nokia)
$regular_expression8='(-)'; // Any Single Character (-)
$regular_expression9='(\w)'; // Word (asha)
$regular_expression10='(-)'; // Any Single Character (-)
$regular_expression11='(\d)'; // Integer Number (253)
if ($c=preg_match_all ("/".$regular_expression1.$regular_expression2.$regular_expression3.$regular_expression4.$regular_expression5.$regular_expression6.$regular_expression7.$regular_expression8.$regular_expression9.$regular_expression10.$regular_expression11."/is", $text1))
{
echo "a-b-1/d-e-2 format string";
}
else
{
echo "Not in a-b-1/d-e-2";
}
echo "<br>------------------------<br>"; //just for separation
if ($c=preg_match_all ("/".$regular_expression1.$regular_expression2.$regular_expression3.$regular_expression4.$regular_expression5."/is", $text2))
{
echo "a-b-1 formate string";
}
else
{
echo "Not in a-b-1 format";
}