PHP : Extract part of a string starting from the middle
Extracting part of the string is a fairly common task in programming and sometimes it can be a bit challenging to extract string starting from a middle of a larger string.
To illustrate the problem here. Let say your :
Problem :
You have a string that looks like this :
expires Friday, December 23, 2014 @ 11:59pm
and you want to final string result to be like :
Friday, December 23, 2014
Solutions :
First solution :
Use substr(), strlen() and strpos() functions
$string = "expires Friday, December 23, 2014 @ 11:59pm";
$final = substr($string, 14, strpos($string, '@') - strlen($string));
Second solution :
Which is more efficient, but less simpler to grasp for those not familiar with regular expression
$string = "expires Friday, December 23, 2014 @ 11:59pm";
$final = preg_replace('/expires\s*(.*?)@/', '\1', $string);
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.9k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+8.9k Golang : Random integer with rand.Seed() within a given range
+6.8k Golang : Reverse by word
+12.4k Golang : 2 dimensional array example
+8.4k Golang : Oanda bot with Telegram and RSI example
+26.2k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+28.1k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+15.3k JavaScript/JQuery : Detect or intercept enter key pressed example
+46.4k Golang : Read tab delimited file with encoding/csv package
+13.9k Golang : Check if an integer is negative or positive
+23.7k Golang : Read a file into an array or slice example
+7.6k Golang : Dealing with struct's private part