Question

I am trying to divide a string with hashtags into the single hashtag.

I am using this code:

preg_match_all('/#([^\s]+)/', $str, $matches);

#test #test #test #example

This one works fine if a user inserts the hashtags with spaces. But what about if they follow each other directly?

#test#test#test#example
Was it helpful?

Solution

Try this:

preg_match_all('/#(\w+)/', $str, $matches);

Example:

<?php
$str = '#test #test2 #123 qwe asd #rere#dada';
preg_match_all('/#(\w+)/', $str, $matches);
var_export($matches);

Output:

array (
  0 => 
  array (
    0 => '#test',
    1 => '#test2',
    2 => '#123',
    3 => '#rere',
    4 => '#dada',
  ),
  1 => 
  array (
    0 => 'test',
    1 => 'test2',
    2 => '123',
    3 => 'rere',
    4 => 'dada',
  ),
)

I think learning RegEx will help you solve these problems.

OTHER TIPS

You could do

$tags = explode('#', $string);
foreach($tags as $key => $tag)
  $tags[$key] = '#' . $tag;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top