Reputation: 3157
Im trying to create a function to check for a substring within a string in php.
public static function stringCheck ($string, $substring) {
$patern = "/".$substring."/";
if (preg_match($substring, string) {
return true;
}
else return false;
}
but if i enter a special character used in preg_match (^.[$()|*+?{) it screws up the search.
I tried something like the code below but that didnt work
$speicalChar = '/(\^|\.|\[|\$|\(|\)|\*|\+|\?|\{|\\)/';
Anyone have a solution or maybe an alternative to preg_match. keep in mind that i want to be able to check for symbols too. I tried using strstr but had issues with symbols.
Thanks =]
Upvotes: 0
Views: 8316
Reputation: 816272
Is there any reason why you want to use preg_match
? Does it have to be a regular expression? What about strpos()
?
Returns the numeric position of the first occurrence of needle in the haystack string.
public static function stringCheck ($string, $substring) {
return (strpos($string, $substring) !== false);
}
If you don't have a reason to use regular expressions, don't use them.
Update:
Regarding the comment about public static
: Don't create classes to collect functions (it looks like you are doing this here). That does not make sense. Just create normal functions and include them in your scripts. Use classes for real OOP.
Btw. you should consider a more expressive name for your function. stringCheck
is pretty vague (what does it check?).
Upvotes: 4
Reputation: 723428
$pattern = '/' . preg_quote($substring, '/') . '/';
This escapes special characters for you. Also pass in '/'
so it gets escaped as well since you're using it as a delimiter.
Another thing, fixes for some typos in your if condition:
if (preg_match($pattern, $string)) {
Upvotes: 5