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
+13.9k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+5.6k Swift : Get substring with rangeOfString() function example
+10k Golang : Test a slice of integers for odd and even numbers
+7.5k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+5.3k Unix/Linux/MacOSx : How to remove an environment variable ?
+13.8k Golang : convert(cast) string to float value
+14.5k Golang : Reset buffer example
+7.6k Golang : Test if an input is an Armstrong number example
+21.7k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+48.5k Golang : Upload file from web browser to server
+22.9k Golang : Test file read write permission example
+19.2k Golang : Get host name or domain name from IP address