Jump to content
gongpex

php pregmatch find string contain hashtag only

Recommended Posts

Hello everyone,

I have code:

$a = ' asasc #aaa cscv #ccc';

if (preg_match('/\#(\w+)/',$a, $matches)) {
            print_r($matches);
 }

this result are : 

Array ( [0] => #aaa [1] => aaa )

that result is not my expectation, my expectation if the result :

Array ( [0] => #aaa [1] => #ccc )

Q So in other word how to make so that preg_match return only the word start with # only.

please someone help me

Thanks

Share this post


Link to post
Share on other sites
<?php
$a = explode(' ','asasc #aaa cscv #ccc');
$c=[];
foreach($a as $b){
if (preg_match('/\#(\w+)/',$b,$matches)) 
{
      $c[]= $matches[0];
 }
}
print_r($c);
Edited by dsonesuk

Share this post


Link to post
Share on other sites

$matches always return 2 array elements, first with whole string with searched for value, the second without. You have gather the first then store it while looping through all individual words added into array using explode().

Edited by dsonesuk

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...