Jump to content

preg_match_all array and foreach [warning: noob question]


Recommended Posts

hey guys!

 

Im trying to get hashtags out of a string.

The function works so far- but i cant transfer the insides of the preg_match_all array into the string.

 

A hint would be fine already.

 

Thanks in advance- and here is some code

 

 

<?php
//example string
$strcontent = "ima string... #wat #taggy #taggytag im in your stringz, stealing your charz!";
  
//find hashtags
preg_match_all("/(#\w+)/", $strcontent, $matches);
echo $matches;            //the output is just "array" -> why?
foreach ($matches as $match)
{
//  $tempmatch=$match[1]; #####like this?
        //hiding the hashtags via span
$strtemp="<br>ima span<br>" . $match . "<br>ima /span<br>" . $strcontent;
$strcontent = $strtemp;
echo $strcontent;
}
#echo $strcontent;
  
  # <span style="display:none;"></span>  
?>

1)  It echoes "Array" because you're trying to echo an array, when you need to be using print_r()

 

2)  preg_match_all makes a multi-dimensional array with an internal array for each group of matches.  Therefore...

 

3)  Your loop should be on $matches[1] which will contain all of the matches for your first capture group (the hashtags)

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.   Restore formatting

  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.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.