There is a string like

text text text @hello text text 

How can I pull out @hello namely everything that starts from @ and before the space Tried through explode and strstr, something didn’t work. It turns out to find @hello and further to the end of the line, but I just need @hello

  • slightly faster two explode - splash58
  • Well, then even faster to cycle through the line - DNS
  • strstr(strstr($text, '@'), ' ', true); - E_p

3 answers 3

Here it is. Simply and easily.

 $text = "text text text @hello text text "; $a = strstr($text, '@'); // отсекаем всё слева $pos = strpos($a, " "); // узнаём сколько знаков до пробела справа $final = substr($a, 0, $pos); // отступим $pos количество символов, и удалим всё справа echo $final; 


Here is even easier:

 $text = "text text text @hello text text "; $a = strstr($text, '@'); // обрезаем все слева до @ $b = strstr($a, ' ', true); // если true, то обрезка будет справа, обрезаем после пробела echo $b; 


A shortened view: (author @E_p)

 $text = "text text text @hello text text "; $a = strstr(strstr($text, '@'), ' ', true); echo $a; 
  • He also displays the text, but you need hello - zkolya
  • hmm, strange, I tried it here, but still / just displays the first element of phptester.net - zkolya
  • @zkolya Redid it differently ... Apparently the function array_search () is looking for the whole string, not the character in the string. - Andrei Dinevich
  • one
    Thank you, cool, everything works - zkolya
  • one
    If you copy someone's answer to yours, then you can mark whose authorship it is. - E_p

For example, a regular expression

 $search = 'text text text @hello text text'; $patt = '~@[\S]+~'; preg_match_all($patt, $search, $all); echo '<pre>'; var_dump($all); echo '</pre>'; 

    I think the solutions above are a better option, but this one also has the right to life:

     $text = "text text text @hello text text "; function findAfterDogText($text) { $arr = explode(' ', $text); foreach ($arr as $value) { if ($value[0]=='@') { return substr($value, 1); } } return null; } var_dump(findAfterDogText($text));