Return only matched occurrences with strstr()

Say I have the following string:

$string = 'Great @jason I think @sally would love it too.'

I'm using:

$mentions = strstr($string, '@');
echo $mentions 

Which outputs

@jason I think @sally would love it too.

Desired output

@jason @sally

I just can't figure how to do this in php, in js I simply do:

hashtags = /\@\w+/g;
var matches = string.match(hashtags);
alert(matches);

preg_match() in php returns a boolean, so the closest I can get is with strstr()... but returns the whole string after the first match.

Answers


You can use preg_match_all with that same regex:

<?php

$string = 'Great @jason I think @sally would love it too.';
preg_match_all("/@\w+/", $string, $matches);

var_dump($matches);

?>

Demo: http://ideone.com/NgrRvH


Need Your Help

Print the substring in small font size in pdf

java string string-concatenation pdf-writer

I using the below code to print a string in pdf which give me an out put of the same sized string i want to make the last two string in different font size. how can i do this ?

What is the widget name of the Kde bar used in program like Kate? (image inside)

c++ reference toolbar kde

What is the object name of the Kde bar that provide buttons to hide/unhide widgets? I can't find on kde official API references. It's used in program like Kate, Kdevelop. Here the screenshot of the...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.