I am seeking to extract neighbor elements of a string in PHP for eg a string is like 11,12,13,14,15
If I pass neighbor(12) it should return 11 and 13. I am looking to do this without using explode for memory conservation (the example is a very small string) where as actual string will vary but will be separated by commas.
Edit IN case of first and last null should be returned for eg neighbor(15) before => 14 after => null
You can use a regular expression:
preg_match('/(?:(\d+),)?\b12\b(?:,(\d+))?/', $string, $match);
The neighbors will be in $match[1]
and $match[2]
.