regex - PHP - Extract characters before and after first space
644
Can't seem to get this one. I would like to get the first 2 characters from the word before the first space and first 3 characters after the first space.
Not sure if break up the word in [0], [1] would work, but regex might work.
$string = "Bobby Ryan";
$output = 'BoRya';
Thanks
Answer
Solution:
What have you tried?
suggestion: explode() your string on the space character, get the first and last values in the array by index, then use substr() to fetch the characters you require.
Answer
Solution:
This should work correctly.
Answer
Solution:
From
explode()
's manual entry: (http://www.php.net/explode) -array explode ( string $delimiter , string $string [, int $limit ] )
.the optional
$limit
parameter indicates into how many pieces the string should be exploded to, and considering what you want to achieve, along withsubstr()
(http://www.php.net/substr):will break the string into two strings right at the first space character, and then form the output from the first two characters of whatever was before the space, and the first three characters of whatever was after the space.
Answer
Solution:
Answer
Solution:
If you want to use regex only:
Answer
Solution:
You must first split the string into parts. Look at explode or some kind of String tokinizer. You must then use a substring function to get parts of the strings.
The function could have several more parameter. The start of first and second string. (The 0s in substring function) and a spesified delimiter. (Change to explode($delimiter, $string);
Hope this helps.