1

I have the following php function which i wrote a while ago. Now however, I'm moving some parsing/matching to the client side.

function artist_name_to_regex($art_name){
    $regex_part =   preg_quote($art_name);
    $regex_part =   preg_replace('('|\')', '.+', $regex_part);
    $regex_part =   preg_replace('/ /i', '\s?', $regex_part);
    $regex_part =   preg_replace('/(and|&|&|\+)/i', '(and|&|&|\+)', $regex_part);
    return $regex_part;
}

I'd like to call it like this from js:

var regex = artist_name_to_regex('David & the Smokey Sea Horses!');
if(some_str.match(/regex/ig)){
    alert('match found!');
}

I need to modify the top function so that it:

a) is written in javascript

b) returns a regex that will work with javascipt

1
  • I don't understand, they are both PCRE right? As for the php, doesen't '('|\')' need to be '/../' ? As for '/(and|&|&|\+)/i', & will match before &, and it seems they are all single replacements as opposed to global. I'm no expert on php yet. Can you give specific examples of how you are trying to condition the regex? Commented Mar 1, 2011 at 19:05

1 Answer 1

1

Why do you need to construct a regular expression like that? It looks as if you need to know whether a string occurs within another one...

Which can much more easily be tested like this:

if (some_str.indexOf('David & the Smokey Sea Horses!') !== -1) {
    alert('match found!');
}

Otherwise, it's fairly easy to create a regular expression from a string:

function createRegex(pattern) {
    pattern = pattern.replace(/'/g, '.+');
    pattern = pattern.replace(/ /g, '\\s?');
    pattern = pattern.replace(/(and|&|&|\+)/ig, '(and|&|&|\\+)');
    return new RegExp(pattern, 'gi');
}

var customRegex = createRegex('David & the Smokey Sea Horses!');
if (some_str.match(customRegex)) {
    alert('match found!');
}
2
  • From the question, it looks like OP also wants "David and the Smokey"... and "David & the Smokey" to pass the test Commented Mar 1, 2011 at 20:08
  • Yes, I’ve been porting his replacements to Javascript as well. Commented Mar 1, 2011 at 20:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.