Reputation: 2976
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;
Upvotes: 2
Views: 184
Reputation: 4202
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.
Upvotes: 1