Search code examples
phppreg-match

how to know position of the word that preg_match has found


I want to find a special word, using preg_match in a string and echo 100 characters that comes after it.
For this, i need to know the position of the word that preg_match() has found.

Perhaps you will advise me to use strpos() for finding its position but the problem with strpos() is for instance when I have two words of "smart" and "art" in my string and "smart" came before "art", strpos finds "smart" while I wanted it to find "art". That's why I decided to use preg_match().

the below code is the one I have written:

<?php pattern = "/\b' .$data[title]. '\b/i" ; 
      $article= $data['description'];     
      preg_match($pattern, $article, $matches);    echo '. $matches .' ;
?>

for example :

  <?php $pattern = "/\b' .art. '\b/i" ;   
        $article= "I didn’t think parents do not like that either…but son is so smart.who is studying art therapy";      
        preg_match($pattern, $article, $matches);        
        echo '. $art .' ;  
  ?>

Solution

  • Try this one to get the 100 characters directly:

     <?php 
       $pattern = "/\bart\b(.{100})/i";   
       $article= "I didn’t think parents do not like that either…but son is so smart.who is studying art therapy I didn’t think parents do not like that either…but son is so smart I didn’t think parents do not like that either…but son is so smart";      
      preg_match($pattern, $article, $matches);        
      print_r($matches);  
      echo 'Length: '+strlen($matches[1])
    ?>
    

    Output:

    Array
    (
      [0] => art therapy I didn’t think parents do not like that either…but son is so smart I didn’t think par
      [1] =>  therapy I didn’t think parents do not like that either…but son is so smart I didn’t think par
    )
    Length: 100