code_junkie

Writing a simple preg_replace in PHP

Nov 11th, 2011
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. <?php
  2.  
  3. $input = "[youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&hl=en&fs=1]";
  4.  
  5. if ( preg_match('/[youtube=.*?v=(.*?)&.*?]/i', $input, $matches ) )
  6. {
  7. $sanitizedVideoId = urlencode( strip_tags( $matches[1] ) );
  8. echo 'param name="movie" value="http://www.youtube.com/v/' . $sanitizedVideoId . '&hl=en&fs=1&rel=0';
  9. } else {
  10. // Not valid input
  11. }
  12.  
  13. <?php
  14.  
  15. $input = "[youtube=http://www.youtube.com/watch?v="><script src="http://example.com/xss.js"></script>&hl=en&fs=1]";
  16.  
  17. // Is vulnerable to XSS
  18. echo preg_replace('/[youtube=.*?v=(.*?)&.*?]/i', 'param name="movie" value="http://www.youtube.com/v/$1&hl=en&fs=1&rel=0', $input );
  19. echo "n";
  20.  
  21. // Prevents XSS
  22. if ( preg_match('/[youtube=.*?v=(.*?)&.*?]/i', $input, $matches ) )
  23. {
  24. $sanitizedVideoId = urlencode( strip_tags( $matches[1] ) );
  25. echo 'param name="movie" value="http://www.youtube.com/v/' . $sanitizedVideoId . '&hl=en&fs=1&rel=0';
  26. } else {
  27. // Not valid input
  28. }
  29.  
  30. $str = preg_replace('/[youtube=.*?v=([a-z0-9_-]+?)&.*?]/i', 'param name="movie" value="http://www.youtube.com/v/$1&hl=en&fs=1&rel=0', $str);
  31.  
  32. / - Start of RE
  33. [ - A literal [ ([ is a special character so it needs escaping)
  34. youtube= - Make sure we've got the right tag
  35. .*? - Any old rubbish, but don't be greedy; stop when we reach...
  36. v= - ...this text
  37. ([a-z0-9_-]+?) - Take some more text (just z-a 0-9 _ and -), and don't be greedy. Capture it using (). This will get put in $1
  38. &.*?] - the junk up to the ending ]
  39. /i - end the RE and make it case-insensitive for the hell of it
  40.  
  41. $originalURL = 'http://www.youtube.com/watch?v=VIDEO_ID_HERE&hl=en&fs=1';
  42.  
  43. foreach( parse_url( $originalURL, PHP_URL_QUERY) as $keyvalue )
  44. {
  45. if ( strlen( $keyvalue ) > 2 && substr( $keyvalue, 0, 2 ) == 'v=' )
  46. {
  47. $videoId = substr( $keyvalue, 2 );
  48. break;
  49. }
  50. }
  51.  
  52. $newURL = sprintf( 'http://www.youtube.com/v/%s/whatever/else', url_encode( $videoId ) );
  53.  
  54. $embedString = 'youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&hl=en&fs=1';
  55. preg_match('/v=([^&]*)/',$embedstring,$matches);
  56. echo 'param name="movie" value="http://www.youtube.com/v/'.$matches[1].'&hl=en&fs=1&rel=0';
  57.  
  58. $str = preg_replace('/[youtube=[^]]*?v=([^]]*?)&[^]]*?]/i', ...)
Add Comment
Please, Sign In to add comment