search string from another string and add these string to array [closed]
Question
My string is:
$str = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
I want to get #fox, #dog
and #lazy
from that string and also every words that contains#
and I want to add these string to an array like that:
$array = array(
[0]=>'#fox',
[1]=>'#dog',
[2]=>'#lazy',
);
Anyone who can help me.. Please. Thanks a lot!
Solution
You could make use of this regular expression '/#(\w+)/'
<?php
$str = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
preg_match_all('/#(\w+)/', $str, $matches);
array_walk($matches[1],function (&$v){ $v='#'.$v;});
print_r($matches[1]);
OUTPUT :
Array
(
[0] => #fox
[1] => #dog
[2] => #lazy
)
OTHER TIPS
Here it is:
$s = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
$r = array();
preg_match_all('/(?<!\w)#\w+/', $s,$r);
print_r($r);
using the regex whith preg_match_all
you get a single array with all words starting with #
contained in the string.
$str = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
$pattern = '/(?<!\w)#\w+/';
preg_match_all($pattern, $str , $matches);
print_r($matches);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow