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
+4.3k Unix/Linux/MacOSx : How to remove an environment variable ?
+3.7k Linux/MacOSX : How to symlink a file?
+9.7k Golang : Calculate Relative Strength Index(RSI) example
+8.5k Golang : Turn string or text file into slice example
+18.1k Golang : Compare floating-point numbers
+10.4k Golang : Change date format to yyyy-mm-dd
+18.2k Golang : Archive directory with tar and gzip
+9.1k Golang : Convert file unix timestamp to UTC time example
+4k Golang : Convert lines of string into list for delete and insert operation
+43.9k Golang : Read tab delimited file with encoding/csv package
+16.5k Golang : Get all upper case or lower case characters from string example
+27.7k Golang : How to create new XML file ?