How do I get a word in php that contains a colon (:)?

I've got the word Hello How are you :chinu i am :good

I want to get the word out, which contains :

as :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 the code I am getting Array ( [0] => : [1] => )

But not getting the exact text. Please help me.

Thanks Chin

+3


source to share


3 answers


To get all the matches you need to use preg_match_all()

. As far as your regex is concerned, your negative class is backward; matching any character: :

, ^

"zero or more" time and will not match the expected one.

You pointed out in the comments about "records" that are printed twice, this is because you are printing an array $matches

and not printing an index group , which only displays the matching results.



preg_match_all('/:\S+/', $string, $matches);
print_r($matches[0]);

      

+6


source


:\S+

      

Try it. Check out the demo.



http://regex101.com/r/tF5fT5/43

$re = "/:\\S+/im";
$str = "Hello How are you :chinu i am :good";

preg_match_all($re, $str, $matches);

      

+6


source


So, you need to do something like the following to match the characters up to the place:

preg_match_all('/:[^ ]+/', $string, $matches);

      

or if you are looking for alpha range characters only, you can use the following:

preg_match_all('/:[A-Za-z]+/', $string, $matches);

      

At this point, the array you were looking for will be $matches[0]

.

print_r($matches)

print_r($matches[0])

      

You can always reassign the subscript match array something like this:

$matchesArray = $matches[0]

      

+3


source







All Articles