Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get word in php which contains colon(:)?

I have a word Hello How are you :chinu i am :good i want to get the word which contains : like :chinu and :good

My code:

<?php
  //$string='Hello How are you :chinu i am :good';
  //echo strtok($string, ':');  

  $string='Hello How are you :chinu i am :good';
  preg_match('/:([:^]*)/', $string, $matches);
  print_r($matches);
?>

Above code i am getting Array ( [0] => : [1] => ) But not getting the exact text. Please help me.

Thanks Chinu

like image 602
Developer Avatar asked Dec 04 '22 05:12

Developer


1 Answers

To get all matches you need to use preg_match_all(). As far as your regular expression goes your negated class is backwards; matching any character of: :, ^ "zero or more" times and will not match what you expect.

You stated in the comments about the "records" being printed twice, this is because you print the $matches array itself instead of printing the group index which only displays the match results.

preg_match_all('/:\S+/', $string, $matches);
print_r($matches[0]);
like image 64
hwnd Avatar answered Dec 21 '22 05:12

hwnd