wordpress - Undefined Offset / PHP error -
i'm using wordpress plugin contains function, plugin developers not being particularly quick respond.
it supposed video id youtube url, instead i'm getting "undefined offset: 1" error. there coding error i'm missing?
here function:
function youtube_id_from_url($url) { $pattern = '%^# match youtube url (?:https?://)? # optional scheme. either http or https (?:www\.)? # optional www subdomain (?: # group host alternatives youtu\.be/ # either youtu.be, | youtube\.com # or youtube.com (?: # group path alternatives /embed/ # either /embed/ | /v/ # or /v/ | /watch\?v= # or /watch\?v= ) # end path alternatives. ) # end host alternatives. ([\w-]{10,12}) # allow 10-12 11 char youtube id. $%x' ; $result = preg_match($pattern, $url, $matches); if (false !== $result) { return $matches[1]; } return false; } i tried doing print_r see array $matches looks like, , seemed empty array, tried echoing $result , returned 0, mean preg_match() isn't finding match, correct? if so, can figure out what's wrong $pattern make return 0.
update: apparently there's other function taking url , making link out of , saving $url variable. if echo $url variable prints <a href="youtube url">youtube url</a>.
so explains error how can modify regex accommodate html markup?
preg_match return false if error occurs, , in case you're wanting know if there either matches or no matches. should able switch line:
if (false !== $result) { to
if ( isset( $matches[1] ) ) { or
if ( $result && isset( $matches[1] ) ) { as phil points out, need is:
if( $result ) { full revised function complete phil's modification regex:
function youtube_id_from_url($url) { $pattern = '%^# match youtube url (?:https?://)? # optional scheme. either http or https (?:www\.)? # optional www subdomain (?: # group host alternatives youtu\.be/ # either youtu.be, | youtube\.com # or youtube.com (?: # group path alternatives /embed/ # either /embed/ | /v/ # or /v/ | /watch\?v= # or /watch\?v= ) # end path alternatives. ) # end host alternatives. ([\w-]{10,12}) # allow 10-12 11 char youtube id. &?.*$%x' ; $result = preg_match($pattern, $url, $matches); if ($result) { return $matches[1]; } return false; }
Comments
Post a Comment