[英]Matching a Pattern in PHP
I am trying to validate whether or not a string contains and starts with BA700
. 我正在尝试验证字符串是否包含
BA700
并以BA700
。 I have tried using the preg_match()
function in PHP but I have not had any luck. 我试过在PHP中使用
preg_match()
函数,但是没有运气。 My code is below: 我的代码如下:
preg_match('/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/', $search))
This does not work unfortunately. 不幸的是,这是行不通的。 Any ideas?
有任何想法吗?
UPDATES CODE: 更新代码:
$needle = 'BA700';
$haystack = 'BA70012345';
if (stripos($haystack, $needle)) {
echo 'Found!';
}
This does not work for me either 这对我也不起作用
Try with substr
like 尝试使用
substr
喜欢
$needle = 'BA700';
$haystack = 'BA70012345';
if(substr($haystack, 0, 4) == $needle) {
echo "Valid";
} else {
echo "In Valid";
}
You can also check regards with the case by changing both of them in either UPPER
or LOWER
like 您还可以通过在
UPPER
或LOWER
更改两者来检查情况
if(strtoupper(substr($haystack, 0, 4)) == $needle) {
echo "Valid";
} else {
echo "In Valid";
}
Here is how to correctly use stripos 这是正确使用Stripos的方法
if (stripos($haystack, $needle) !== false) {
echo 'Found!';
}
Maybe I am taking this a little too literally, but: 也许我从字面上看有点过分,但是:
if (strncmp($string, 'BA700', 5) === 0) {
// Contains and begins with 'BA700'
}
If the BA700
is case-insensitive then: 如果
BA700
不区分大小写,则:
if (strncasecmp($string, 'ba700', 5) === 0) {
// Contains and begins with 'ba700'
}
There should not be much more to it than that. 除此以外,不应该有太多其他事情了。
The regular expression, in case you want to know, is: 如果您想知道,正则表达式为:
if (preg_match('/^BA700/', $string) === 1) {
// Contains and begins with 'ba700'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.