-1

对不起,我的英语不好。我有一个问题,我想比较两个不同的字符串使用reg exp。第一个字符串的结构类似于ab-1,例如:mobile-phone-1。第二个字符串的结构类似于ab-1/de-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:不要太在意代码演示

4

3 回答 3

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))

'i' 最后是为了区分大小写。

于 2013-07-11T09:50:34.967 回答
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]+#';
于 2013-07-11T09:24:44.850 回答
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";
  }
于 2013-07-11T09:55:45.487 回答