Last active
April 8, 2018 02:36
-
-
Save benjibee/8974203 to your computer and use it in GitHub Desktop.
Extracts any one URL in the given string and assigns it to a variable.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$new_entry['url'] = FALSE; | |
$new_entry['description'] = 'Hello there! example.com'; | |
$pattern_url = "`(" | |
. "(https?://)?" | |
. "([a-z\d-]+\.)+" | |
. "(MUSEUM|TRAVEL|AERO|ARPA|ASIA|EDU|GOV|MIL|MOBI|COOP|INFO|NAME|BIZ|CAT|COM|INT|JOBS|NET|ORG|PRO|TEL|A[CDEFGILMNOQRSTUWXZ]|B[ABDEFGHIJLMNORSTVWYZ]|C[ACDFGHIKLMNORUVXYZ]|D[EJKMOZ]|E[CEGHRSTU]|F[IJKMOR]|G[ABDEFGHILMNPQRSTUWY]|H[KMNRTU]|I[DELMNOQRST]|J[EMOP]|K[EGHIMNPRWYZ]|L[ABCIKRSTUVY]|M[ACDEFGHKLMNOPQRSTUVWXYZ]|N[ACEFGILOPRUZ]|OM|P[AEFGHKLMNRSTWY]|QA|R[EOSUW]|S[ABCDEGHIJKLMNORTUVYZ]|T[CDFGHJKLMNOPRTVWZ]|U[AGKMSYZ]|V[ACEGINU]|W[FS]|Y[ETU]|Z[AMW])+" | |
. "(:\d+)?" | |
. "((/([a-z0-9\._/~%\-\+&\#\?!=\(\)@]+)?)*)" | |
. ")`i"; | |
if ( preg_match( $pattern_url, $new_entry['description'], $match ) ) { | |
$url = $match[0]; | |
if ( FALSE === strpos($url, '://') ) { | |
$url = 'http://' . $url; | |
} | |
$new_entry['url'] = htmlspecialchars( $url ); | |
$new_entry['description'] = str_replace( $match[0], '', $new_entry['description'] ); | |
} | |
echo $new_entry['description']; | |
echo $new_entry['url'] ? ' url: '.$new_entry['url'] : ''; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment