Muhammad Haroon
Muhammad Haroon

Reputation: 23

preg_match not working on long regular expressions

I want to match a keyword using preg_match in php. regular expression is working perfectly on www.regexr.com but not in my php code. can someone help. Thankyou.

<?php

$regexx="/[sS]+([\s\t\r]*[\.\~\`\!\@\#\$\%\^\&\*\(\)\-\_\+\=\[\]\{\}\;\:\"\'\\\|\,\.\<\>\/\?\d\w]*)+[hH]+([\s\t\r]*[\.\~\`\!\@\#\$\%\^\&\*\(\)\-\_\+\=\[\]\{\}\;\:\"\'\\\|\,\.\<\>\/\?\d\w]*)+[aA]*([\s\t\r]*[\.\~\`\!\@\#\$\%\^\&\*\(\)\-\_\+\=\[\]\{\}\;\:\"\'\\\|\,\.\<\>\/\?\d\w]*)+[rR]*([\s\t\r]*[\.\~\`\!\@\#\$\%\^\&\*\(\)\-\_\+\=\[\]\{\}\;\:\"\'\\\|\,\.\<\>\/\?\d\w]*)+[eE]*
/";
if (preg_match($regexx, "S-hare"))
{
    echo 'succeeded';
}
else
{
    echo 'failed';
}

?>

Upvotes: 1

Views: 131

Answers (1)

Cyrbil
Cyrbil

Reputation: 6478

Based on your comment:

I want to match the word 'share' written in any format. for example.. any special character or space in between 'share' would be detected.

I would suggest to simply remove every non alphabetics characters then match what is left.

var_dump($str = preg_replace("/[^a-z]/i", "", "sh@a/#~r:  e !!!"));
var_dump($str === "share");

A raw single regex solution could be:
/[^a-z]*s[^a-z]*h[^a-z]*a[^a-z]*r[^a-z]*e[^a-z]*/i
Which is simple share and [^a-z]* to match any non alphabetics series of characters between every letters.

Upvotes: 1

Related Questions