Question

I have text like:

$tagPossible = '365 Wallpapers now available on Nokia Store for #NokiaX family @nokiadeveloper @nokia';

There are two words in this string with @nokiadeveloper and @nokia

What i have been done is that this two strings ( which can be X ) i want to store into my database.

$tag = strstr($tagPossible, '@');
echo $converTag = str_replace('@', '', $tag);

This is my Output: nokiadeveloper nokia

Becouse there are two tags, i want to import them as two rows into my database. So i need to be specific when import this strings.

How i'm able to select this strings? I want to select only nokiadeveloper and nokia as array.

Thanks!

Was it helpful?

Solution

Use preg_match_all() with a positive lookahead to extract all the required strings:

(?<=\s)@(\w+)

Explanation:

  • (?<=\s) - if preceded by a whitespace character
  • @ - match literal @ character
  • (\w+) - match (and capture) any word character [A-Za-z0-9_]

Code:

$ok = preg_match_all('/(?<=\s)@(\w+)/', $tagPossible, $matches);

if ($ok) {
    $arr = $matches[1];
}

print_r($arr);

Output:

Array
(
    [0] => nokiadeveloper
    [1] => nokia
)

OTHER TIPS

In addition, here's another solution that maybe helpful. Just because I hate Regex:

$tag = strstr($tagPossible, '@');    
$tags = explode('@', $tag);

foreach($tags as $tag) {
    echo trim($tag). PHP_EOL;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top