1

I am using the startsWith() function here startsWith() and endsWith() functions in PHP

But I want it to only match full words.

Currently it will match the following:

hi
high
hiho

But I want it to only match "hi", not the other two words if the input is:

hi there
Community
  • 1
  • 1
John
  • 1,243
  • 4
  • 15
  • 34

2 Answers2

2

You can match it with this regular expression: /^hi$|^hi\s|\shi\s|\shi$/

$test = ['hi', 'hi there', 'high', 'hiho'];
$pattern = '/^hi$|^hi\s|\shi\s|\shi$/';
$matches = [];

foreach ($test as $t) {
    var_dump($t);
    preg_match($pattern, $t, $matches);
    var_dump($matches);
}

Parts explained:

  • ^hi$ - your sting is "hi"
  • ^hi\s - your string starts with hi: "hi "
  • \shi\s - there's a " hi " somewhere in your string
  • \shi$ - your string ends with " hi"

Those parts are glued together with pipe "|", which in regex means "or", so the entire expression is matching any one of the parts

Nenad Mitic
  • 577
  • 4
  • 12
  • I used pattern '/^hi$|^hi\s/' but it does not match 'hi' and 'hi there' which it should in that case? – John Sep 17 '16 at 07:33
0

If you test whole text against hi words, try this:

<?php    
preg_match_all('@hi\s@i',
        "hi me
        hi there
        high
        highlander
        historic
        hire", 
$matches);

var_dump($matches);

enter image description here

Test it - modify here: https://regex101.com/r/tV3jR6/1

pedrouan
  • 12,762
  • 3
  • 58
  • 74