PHP: $words = preg_split("/[\s,_-]+/", "$message");$acronym='';foreach ($words as $w) { $acronym .= $w[0]; if($acronym == '@'){ $mention = substr($w, 1); return false; }} Error : Notice: Uninitialized string offset: 0 Error in line PHP: $acronym .= $w[0];
Foreach() splits an array up for each key/value. You have used foreach() here, which means you can't use $w[0] as it is not an array, but a string, being part of an array. you'll either have to use just $w or not use foreach.
Maybe this would work.... PHP: $words = preg_split("/[\s,_-]+/", "$message");$acronym='';foreach ($words as $w) { $acronym .= $w{0}; if($acronym == '@'){ $mention = substr($w, 1); return false; }} Note that the "$message" is better off without the quotes.
Sorry, I failed to notice the difference apart from using {} instead of []? Also, it would be better to use single quotes for the regex, or escape the backslash.
Yes, but that makes the difference. They want to catch words that begin with "@". So doing $w[0], PHP thinks that $w is an array and you want to get the first element in the array. Doing $w{0}, PHP thinks that $w is a string and you want to get first character in the string.
But aren't they the same for accessing offsets in a string? PHP: $ php -r '$a = "abc"; var_dump($a[0]);'Command line code:1:string(1) "a"
I stand corrected! See this link for the whole explanation: http://www.php.net/manual/en/language.types.string.php#language.types.string.substr