Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find whole word with strpos()

Tags:

php

strpos

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?

like image 614
Simon Thomsen Avatar asked Sep 17 '25 01:09

Simon Thomsen


1 Answers

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];
like image 132
ircmaxell Avatar answered Sep 18 '25 15:09

ircmaxell