4

Hello people :) I'm trying to use strpos() to find whole words in a sentence. But at the moment, it also find the word if it just are a part of another word. For example:

$mystring = "It's a beautiful morning today!";
$findme   = "a";

$pos = strpos($mystring, $findme);

In this example it would find "a" in the word "a" (as it should do), but also in "beautiful" because there is an a in it.

How can i find only whole words and not if it is a part of other words?

Jim
  • 18,673
  • 5
  • 49
  • 65
Simon Thomsen
  • 1,351
  • 7
  • 27
  • 37

3 Answers3

13

This is a job for regex:

$regex = '/\b'.$word.'\b/';

Basically, it's finding the letters surrounded by a word-boundary (the \b bits). So, to find the position:

preg_match($regex, $string, $match, PREG_OFFSET_CAPTURE);
$pos = $match[0][1];
ircmaxell
  • 163,128
  • 34
  • 264
  • 314
  • And if you're not sure where the word ends?. In my case it's a youtube url that might have a random query string attached to it, i just need the position of the beginning and the end of it. – Marcos Di Paolo Jan 03 '20 at 03:02
3

Use regex , with the word boundary delimiter \b, like this :

$mystring = "It's a beautiful morning today!";
preg_match_all('/\ba\b/', $mystring, $matches, PREG_OFFSET_CAPTURE);
var_dump($matches);

returns

array(1) {
  [0]=>
  array(1) {
    [0]=>
    array(2) {
      [0]=>
      string(1) "a"
      [1]=>
      int(5)
    }
  }
}
Xavier Barbosa
  • 3,919
  • 1
  • 20
  • 18
0

regex is hard for beginners, another way and I admit it isn't the best, would be to use
$findme = " a "

Steve
  • 1,371
  • 1
  • 16
  • 38