XF 2.1 Word boundary search

AndyB

Well-known member
In my similar threads add-on, I'm currently using finder with the LIKE function, this works well but it will get results when a word is contained in another word. For example if I search for 'test' I get results when the thread title contains testing.

It appears finder does not support REGEXP.

I can use MySQL and the REGEXP function to accomplish a word boundary and get the results I'm looking for, but is the code below safe?

PHP:
$string = 'test';

$string = \XF::escapeString($string);

$string = '[[:<:]]' . $string . '[[:>:]]';

$db = \XF::db();

$results = $db->fetchAll("
SELECT title
FROM xf_thread
WHERE title REGEXP '$string'
");

Thank you.
 
Got it:

PHP:
$string = 'age';

$string = \XF::escapeString($string);

$string = '[[:<:]]' . $string . '[[:>:]]';

$db = \XF::db();

$results = $db->fetchAll("
SELECT title
FROM xf_thread
WHERE title REGEXP ?
", $string);
 
Can do regexp conditions with the finder too:
Code:
$searchValue = '\'[[:<:]]' . $finder->escapeExpression($title) . '[[:>:]]\'';
$finder->where($finder->expression('title RLIKE  ' . $searchValue));
 
Top Bottom