检查字符串(在//和/之间)是否包含冒号和点

时间:2016-09-12 02:08:13

标签: php regex

我的字符串介于///之间,即。 {sub1}//{string}/{sub2}

如果此字符串包含冒号(一个或多个)和一个点(一个或多个),我怎么知道(可能是最快的方式)?例如:

testsomething//apple:phone./hello -> TRUE (string contains both a colon and a dot)
test1//apple:phone/someth -> FALSE (string doesn't contain a dot)
worl//apple:::ph. one/hello -> TRUE (string contains a colon and a dot)
som//:app.le-phone/thing - TRUE (string contains a colon and a dot)
kor//.apple phone/sor - FALSE (string doesn't contain a colon)
len//:.applephone/fbe - TRUE (string contains a colon and a dot)
bei//apple.phone.:/sse - TRUE (string contains a colon and a dot)
dfsd//apple:phon:e/dsd - FALSE (string doesn't contain a dot)

2 个答案:

答案 0 :(得分:3)

纯粹的strpos尝试

$str="worl//apple:::ph. one/hello";

$x=explode('/',$str); //extract your substring, your examples are regular its always $x[2]

$findme   = '.';
$pos = strpos($x[2], $findme);

$findme   = ':';
$pos2 = strpos($x[2], $findme);

if ($pos !== false && $pos2 !== false) {
echo 'its a bingo'; 
}else{
    echo 'no bingo';
}

答案 1 :(得分:2)

使用preg_match如下:

$string = "testsomething//apple:phone./hello";

preg_match("/\/\/((.*?[:].*?[.].*?)|(.*?[.].*?[:].*?))\//", $string, $match);

print_r($match);

由于您不关心:.的顺序,[:][.]之前和之后。

\/\/的{​​{1}}分界和//是非贪婪的全部。

编辑:

将正则表达式从.*?更新为preg_match("/\/\/(.*?[:.].*?[:.].*?)\//", $string, $match);,因为如果它还有双preg_match("/\/\/((.*?[:].*?[.].*?)|(.*?[.].*?[:].*?))\//", $string, $match);:,则前一个匹配任何内容。只有当冒号和句号都存在时才会匹配,如果缺少任何一个则不匹配。