When the client uploads a string, it needs to match all URLs from the string. how can php implement this? This article describes how to obtain the URL (URL link) in a string in php, mainly using the php regular expression function preg_match_all, for details about the implementation method, refer to the following section. after a Q & A system is launched today, many people are connected to the system. as the business department asks us to filter out the website address, the following is a function for extracting string URLs. the code is as follows:
$ Str = 'this example describes how php matches all URL addresses in a string. Http://www.manongjc.com to share with you for your reference '; preg_match_all ("/http: [\/] {2} [a-z] + [.] {1} [a-z \ d \-] + [.] {1} [a-z \ d] * [\/] * [A-Za-z \ d] * [\/] * [A-Za-z \ d] */", $ str, $ array2); print_r ($ array2 );
The running result is:
( [0] => Array ( [0] => http://www.manongjc.com ))
The preg_match_all function is used here. the usage of this function is as follows:
Preg_match_all-perform global regular expression matching
Syntax:
int preg_match_all ( string pattern, string subject, array matches [, int flags] )
Search all the content that matches the regular expression given by pattern in the subject and put the result in the matches in the order specified by flags.
After the first match is found, the next search starts from the end of the previous match.
Special note: PREG_PATTERN_ORDER and PREG_SET_ORDER
Flags can be a combination of the following tags (note that it is meaningless to combine PREG_PATTERN_ORDER and PREG_SET_ORDER ):
If PREG_PATTERN_ORDER is used
Sort the results to make $ matches [0] an array that matches all modes, $ matches [1] An array consisting of strings that match the child pattern in the first parentheses, and so on. ($ Matches [0] [0] indicates each item in all mode matching, and $ matches [0] [1] indicates the second item in all mode matching, $ matches [1] [0] is used to match the first item in each bracket, and $ matches [1] [0] is used to match the second item in each bracket)
]+>(.*)
]+>|U","example: this is a test
",$out, PREG_PATTERN_ORDER);/* http://www.manongjc.com/article/1591.html */print $out[0][0].", ".$out[0][1]."\n";print $out[1][0].", ".$out[1][1]."\n";?>
Output result:
example: , this is a test
example: , this is a test
For more articles about how to use regular expressions in php to obtain URLs in strings, refer to PHP Chinese website!