rechercher une chaîne à partir d'une autre chaîne et ajouter cette chaîne au tableau [fermé]
Question
Ma chaîne est :
$str = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
Je veux obtenir #fox, #dog
et #lazy
de cette chaîne ainsi que tous les mots contenant#
et je veux ajouter ces chaînes à un tableau comme celui-ci :
$array = array(
[0]=>'#fox',
[1]=>'#dog',
[2]=>'#lazy',
);
Quelqu'un qui peut m'aider..S'il te plaît.Merci beaucoup!
La solution
Vous pouvez utiliser cette expression régulière '/#(\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]);
SORTIR :
Array
(
[0] => #fox
[1] => #dog
[2] => #lazy
)
Autres conseils
C'est ici:
$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);
en utilisant l'expression régulière avec preg_match_all
vous obtenez un seul tableau avec tous les mots commençant par #
contenu dans la chaîne.
$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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow