开发者

Check variable is like a value from another variable in PHP

I need to check the value of $variable1 is 开发者_如何学PythonLIKE another variable2.

There could be something else after a dash but i can't predict what. Is there any kind of wildcard idea in PHP like sql? LIKE variable% ?


If you just want to know if one string is part of another, then do use

  • strpos - Find position of first occurrence of a string

because (quoting the PHP Manual on preg_match)

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.

Example:

$haystack = 'foo-bar';
$needle   = 'o-b';
echo (strpos($haystack, $needle) !== FALSE) ? 'yeah' : 'no';

will output "yeah" because "o-b" is a substring in"foo-bar"


If you mean variable% literally (to match the beginning of a string), this is a case for preg_match().

Slightly modified example from the manual:

$subject = "This string begins with This";
$pattern = '/^This/';
preg_match($pattern, $subject, $matches);
print_r($matches); 

use the /i modifier for case insensitive search.


Well, here's a more robust option:

function isLike($haystack, $needle) {
    $regex = '#^'.preg_quote($needle, '#').'$#i';
    //add support for wildcards
    $regex = str_replace(array('%', '_'), array('.*?', '.?'), $regex);
    return 0 != preg_match($regex, $haystack);
}

Basically, it operates just like MySQL's LIKE. It uses % as a "any character, any number of times" and _ as "anycharacter, zero or one time".

Here's some examples:

isLike('foobarbaz', 'fooba_ba_'); // true
isLike('foobarbaz', 'ba_ba_'); // false
isLike('foobarbaz', 'foodar'); // false
isLike('foobarbaz', 'foo%baz'); // true
isLike('foobarbaz', '%bar%'); // true


Yet another alternative is to use

  • fnmatch() - checks if the passed string would match the given shell wildcard pattern.

Disregard that it says filename in the Manual. It will match anything you throw at it.

Example:

echo fnmatch('foo*', 'foo-bar') ? 'yeah' : 'no';
echo fnmatch('foo-b?r', 'foo-bar') ? 'yeah' : 'no';

would both return "yeah".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜