4

I'm looking for some wildcards to the strpos function similar to those used in preg_replace or preg_match but I can't find any, here is an idea:

<?php
if (strpos("The black\t\t\thorse", "black horse") === false)
  echo "Text NOT found.";
else
  echo "Text found.";
?>

Here the result will be: Text NOT found.

Now I want to use one wildcard to omit spaces or horizontal tab like below:

<?php
if (strpos("The black\t\t\thorse", "black/*HERE THE WILDCARD*/horse") === false)
  echo "Text NOT found.";
else
  echo "Text found.";
?>

And here the idea is that the result is: Text found.

Does anyone know something about ?

Jerska
  • 11,722
  • 4
  • 35
  • 54
Rolige
  • 993
  • 8
  • 10
  • You can't find it because it doesn't exist, `strpos` only does exact matching. If you want wildcards, you have to use regular expressions. – Barmar Oct 20 '13 at 04:57
  • Well, if you need wild cards, then why not use `preg_match` instead? – Amal Murali Oct 20 '13 at 04:57
  • I'm using strpos because i'm trying to find a block of code of 3 lines into one file and replace by another block of text, do you know some function to make this easy ? – Rolige Oct 20 '13 at 06:05

2 Answers2

2

strpos() doesn't match patterns, if you want to match patterns you have to use preg_match() this should work for your situation.

<?php
    if (preg_match('/black[\s]+horse/', "The black\t\t\thorse"))
      echo "Text found.";
    else
      echo "Text not found.";
?>
Praveen
  • 2,400
  • 3
  • 23
  • 30
  • 1
    I'm using `strpos` because i'm trying to find a block of code of 3 lines into one file and replace by another block of text, do you know some function to make this easy ? – Rolige Oct 20 '13 at 06:04
0

If you need the first occurrence of the match then you can use the PREG_OFFSET_CAPTURE flag:

preg_match('/black\shorse/i', "The black\t\t\thorse", $matches, PREG_OFFSET_CAPTURE);
var_dump($matches);

will result in

array(1) { [0]=> array(2) { [0]=> string(13) "black horse" [1]=> int(4) } }

where $matches[0][1] is your position

Konservin
  • 997
  • 1
  • 10
  • 20