Это портирование оказалось, в общем-то, не больше чем забавой, потому что в коде выигрыша не наблюдается. Можно сравнить:
var s = 'aBracadabra';
var regexp = '^abra'
var flags = 'i';
// родной синтаксис из JavaScript
if ( (new RegExp(regexp, flags)).test(s) )
alert('matched !');
// вызов функции, портированной из PHP
if ( preg_match('/'+regexp+'/'+flags, s) )
alert('matched !');
Поэтому код только для тех, кому понравилась идея:
// bool preg_match( string pattern, string subject)
// @pattern should be exactly like this: /pattern/[im]
// ('g' flag is not supported - its for preg_match_all() :)
// Generates global array preg_matches[] with regexp matches.
// Returns true (if matched) or false.
// If matched, preg_matches[0] contains string that satisfied regexp.
var preg_matches = [];
function preg_match(pattern, subject)
{
// extracting pattern body and flags
var m = /^/(.*?)/(.*?)$/.exec(pattern);
// executing regexp
if ((preg_matches = (new RegExp(m[1], m[2])).exec(subject)) == null)
preg_matches = [];
return preg_matches.length > 0 ? true : false;
}
Оставить комментарий: