PHP: compare substrings
Really quick noob question with php:
I'开发者_StackOverflow社区m trying to create a conditional statement where I can check if a variable partially matches a substring.
More specific in my case:
$cal is the name of a file, I want it so if $cal contains ".cfg" it echos some text.
pseudocode:
<?php if ($cal == "*.cfg")
{
echo "Hello ";
}
?>
if (strpos($cal, ".cfg") !== false)
{
echo "some text";
}
EDIT
My proposal for matching exactly "*.cfg":
$cal = "abc.cfgxyz";
$ext = "cfg";
if (strrpos($cal, ".".$ext) === strlen($cal)-strlen($ext)-1)
{
echo "matched";
}
In this case, you can simply look at the last four characters of $cal
using substr
:
if (substr($cal, -4) === '.cfg') {
echo "Hello ";
}
You should look into regular expressions for more complex problems.
if ( preg_match('/\\.cfg$/',$cal) ) echo "Hello ";
should to it. (Assuming you want to match the end of the input string, otherwise, leave out the $
)
for simple patterns strpos will do nicely.
if (strpos ('.cfg', $string) !== false)
{
// etc
}
For more complicated parterns, you want preg_match, which can compare a string against a regular expression.
if (preg_match ('/.*?\.cfg/', $string))
{
// etc
}
The former offers better performance, but the latter is more flexible.
You can use various approaches here. For example:
$cal = explode('.', $cal);
if(last($cal) === "cfg")) {
echo "Hello";
}
Or using regular expressions (which are probably way slower than using strpos for example):
if(preg_match("/\.cfg$", $cal)) {
echo "Hello";
}
I honestly don't know how the explode() version compares to substr() with a negative value (lonesomeday's answer) or strpos() (which has its flaws, Frosty Z's answer). Probably the substr() version is the fastet, while regular expressions are the slowest possible way to do this).
精彩评论