views:

75

answers:

1

I have written this JavaScript that calculate words, but I am unable to convert this JavaScript code to PHP regular expression. Can anyone help me with following code?

return str.replace(/\&\w+;/ig,"")
        .replace(/lt;/g, "<")
        .replace(/gt;/g, ">")
        .replace(/(<([^>]+)>)/ig,"")
        .replace(/^[^A-Za-z0-9-\']+/gi, "")
        .replace(/[^A-Za-z0-9-\']+/gi, " ")
        .split(" ")
        .length - 1;
+1  A: 

PHP does not have a g flag, the closest equivalent is using /is with the replace $limit set to null (all).

After that just explode it by " ".

e.g.

$search = array
(
    '/\&\w+;/is',
    '/lt;/s',
    '/gt;/s',
    '/(<([^>]+)>)/is',
    '/^[^A-Za-z0-9-\\\']+/is',
    '/[^A-Za-z0-9-\\\']+/is'
);

$replacements = array
(
    '',
    '<',
    '>',
    '',
    '',
    '',
);

$input = preg_replace($search, $replacements, $input);
$words = explode(' ', $input);
$wordCount = count($words) - 1;

It's pretty late and I haven't double-checked this. Hope it helps.


Edit: please be careful with escaping the backslash and single-quote.

Denis 'Alpheus' Čahuk
I would have upvoted your answer because of your ‘About me’ text alone, but I don't think that's fair. Nevertheless, it's *way* too late here, too (I think we live in the same timezone), so I'm not going to check your answer now. Oh, and welcome to SO!
Marcel Korpel
Excellent!!!! Worked perfectly! Just a note to others there is a space in the last replacement quotes.
jason