I have the following code:
<?php
$text = 'Hey @Mathew, have u talked with @Jhon today?';
$text = preg_replace('/(^|\s)@([A-Za-z0-9]*)/', '\1<a href="profile.php?user=\\2">@\\2</a>',$text);
?>
And my goal is notify the user was quoted. To do that, I thought: I put all the replaced strings in a array and pick only the name; using the example above, and following the thinking, I have this result:
['Mathew', 'Jhon']
So, how can I have the last result?
You may actually collect matches while performing a regex-based search and replace if you use preg_replace_callback
:
$text = 'Hey @Mathew, have u talked with @Jhon today?';
$names = [];
$text = preg_replace_callback('/(^|\s)@([A-Za-z0-9]*)/', function($m) use (&$names) {
$names[] = $m[2];
return $m[1] . '<a href="profile.php?user=' . $m[2] . '">@' . $m[2] . '</a>';
},$text);
echo "$text
";
print_r($names);
See the PHP demo
Output:
Hey <a href="profile.php?user=Mathew">@Mathew</a>, have u talked with <a href="profile.php?user=Jhon">@Jhon</a> today?
Array
(
[0] => Mathew
[1] => Jhon
)
Note the array variable for the matches is passed to the anonymous function with the use (&$names)
syntax. The $m
is a match object containing the whole match in the first item and captures in the subsequent items.
Before replacing the text you can use preg_match
to find all users in the string:
http://php.net/manual/en/function.preg-match.php
Example:
$text = 'Hey @Mathew, have u talked with @Jhon today?';
preg_match($pattern, $text, $matches);
var_dump($matches);
$text = preg_replace('/(^|\s)@([A-Za-z0-9]*)/', '\1<a href="profile.php?user=\\2">@\\2</a>',$text);
You will have to alter your pattern for this to work.
I guess you can use a regex like /@[a-z0-9]+/sim
, i.e.:
$text = 'Hey @Mathw, have u talked with @Jhon today?';
preg_match_all('/@[a-z0-9]+/sim', $text , $handles_array, PREG_PATTERN_ORDER);
$text = preg_replace('/(@[a-z0-9]+)/sim', '<a href="profile.php?user=$1">$1</a>', $text);
print($text);
print_r($handles_array[0]);
Output:
Hey <a href="profile.php?user=@Mathw">@Mathw</a>, have u talked with <a href="profile.php?user=@Jhon">@Jhon</a> today?Array
(
[0] => @Mathw
[1] => @Jhon
)
Live Demo:
Note:
"It's an example of array..."
I'm not aware of any programing language which arrays are declared with curly brackets {}
, objects normally are. Did you mean brackets []
?