views:

159

answers:

2

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 =]

+4  A: 
$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)) {
BoltClock
wow thanks alot boltclock! preg_quote is exactly what im looking for =]
nubme
+3  A: 

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 stereofrog's 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?).

Felix Kling
+1 for strpos, -0.3 for "public static" rubbish
stereofrog
@stereofrog: Well, I just copied the OPs method signature. Don't blame me! ;) :D
Felix Kling
@stereofrog: how do you get such a nice, rounded float?
BoltClock
@Felix, i'd give another +10 for the update if i could!
stereofrog