Page 1 of 1

Urgent Yet Easy Help Needed With Preg OFFSET CAPTURE

Posted: Fri Sep 07, 2007 9:31 am
by kaisellgren
Hi,

I have a search page. Users can type like abnorm[al][al] and it matches both abnormal and abnormla text (regex). The problem is that how do I know how long is the search word? If I use strlen($search) it says 14 characters (abnorm[al][al]), but I need it to be 8 (abnormal) how would I do this? I am using OFFSET CAPTURE in preg match sentence can I somehow include it there?


Search for: te[sx]t
Results: text, test
Length: 7 (SHOULD BE 4!! :( )

Posted: Fri Sep 07, 2007 10:01 am
by s.dot

Code: Select all

if ($start = strpos($search, '[') && ($end = strpos($search, ']')))
{
    $pos = $end - $start;
    $strlen = strlen($search) - $pos;
    echo $strlen;
}
Untested

Posted: Fri Sep 07, 2007 10:16 am
by kaisellgren
Well yea it works or something like that, but anyone can type also {}, +, ? and other regex metacharacters so that's not going to help me a lot :(

Posted: Fri Sep 07, 2007 10:21 am
by kaisellgren
I got it :)

I used

Code: Select all

foreach ($matches[0] as $array => positions)
echo strlen($positions[0])

Posted: Fri Sep 07, 2007 10:48 am
by s.dot
What happens if someone searches for "a.+"

Posted: Fri Sep 07, 2007 10:51 am
by kaisellgren
scottayy wrote:What happens if someone searches for "a.+"
It says 2, 3, ... depending on the length.

Posted: Fri Sep 07, 2007 10:52 am
by s.dot
If it's a regex match, shouldn't it match all words starting with a? :P Just throwing out hypothetical situations here. Glad you got it to work, and sorry I wasn't able to help!

Posted: Fri Sep 07, 2007 10:54 am
by kaisellgren
scottayy wrote:If it's a regex match, shouldn't it match all words starting with a? :P Just throwing out hypothetical situations here. Glad you got it to work, and sorry I wasn't able to help!
Yes but I am replacing + * and ? characters with \ before inserting in MySQL REGEXP clause. I am accepting {} but with limits.

Posted: Fri Sep 07, 2007 10:55 am
by s.dot
Very nice.