cerca una stringa da un'altra stringa e aggiungi queste stringhe all'array [chiuso]
Domanda
La mia corda è:
$str = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
Voglio ottenere #fox, #dog
e #lazy
da quella stringa e anche da ogni parola che contiene#
e voglio aggiungere queste stringhe a un array del genere:
$array = array(
[0]=>'#fox',
[1]=>'#dog',
[2]=>'#lazy',
);
Chiunque possa aiutarmi..Prego.Grazie mille!
Soluzione
Si potrebbe fare uso di questa espressione regolare '/#(\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]);
USCITA :
Array
(
[0] => #fox
[1] => #dog
[2] => #lazy
)
Altri suggerimenti
Eccolo qui:
$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);
utilizzo della regex whith preg_match_all
ottieni un singolo array con tutte le parole che iniziano con #
contenuto nella stringa.
$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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow