diff --git a/module/VuFindSearch/src/VuFindSearch/Query/Query.php b/module/VuFindSearch/src/VuFindSearch/Query/Query.php index eb9ee259be69a7ebf57a1fd74c8aa4e639f3343d..d6f939e96211f22cd4a2540342ee3fad63bbab38 100644 --- a/module/VuFindSearch/src/VuFindSearch/Query/Query.php +++ b/module/VuFindSearch/src/VuFindSearch/Query/Query.php @@ -149,8 +149,9 @@ class Query extends AbstractQuery */ public function containsTerm($needle) { - // Escape slashes in $needle to avoid regular expression errors: - $needle = str_replace('/', '\/', $needle); + // Escape characters with special meaning in regular expressions to avoid + // errors: + $needle = preg_quote($needle); return (bool)preg_match("/\b$needle\b/u", $this->getString()); } @@ -177,7 +178,7 @@ class Query extends AbstractQuery { // Escape $from so it is regular expression safe (just in case it // includes any weird punctuation -- unlikely but possible): - $from = addcslashes($from, '\^$.[]|()?*+{}/'); + $from = preg_quote($from); // If our "from" pattern contains non-word characters, we can't use word // boundaries for matching. We want to try to use word boundaries when diff --git a/module/VuFindSearch/tests/unit-tests/src/VuFindTest/Query/QueryTest.php b/module/VuFindSearch/tests/unit-tests/src/VuFindTest/Query/QueryTest.php index a035877b080233224838ab002506ea7d89c4dcf1..0f4983f13c188b025b74a0a65b85c22b90328f63 100644 --- a/module/VuFindSearch/tests/unit-tests/src/VuFindTest/Query/QueryTest.php +++ b/module/VuFindSearch/tests/unit-tests/src/VuFindTest/Query/QueryTest.php @@ -49,11 +49,12 @@ class QueryTest extends PHPUnit_Framework_TestCase */ public function testContainsTerm() { - $q = new Query('test query'); + $q = new Query('test query we<(ird'); - // Should contain both actual terms: + // Should contain all actual terms (even those containing regex chars): $this->assertTrue($q->containsTerm('test')); $this->assertTrue($q->containsTerm('query')); + $this->assertTrue($q->containsTerm('we<(ird')); // Should not contain a non-present term: $this->assertFalse($q->containsTerm('garbage')); @@ -62,6 +63,18 @@ class QueryTest extends PHPUnit_Framework_TestCase $this->assertFalse($q->containsTerm('tes')); } + /** + * Test replaceTerm() method + * + * @return void + */ + public function testReplaceTerm() + { + $q = new Query('test query we<(ird'); + $q->replaceTerm('we<(ird', 'we>(ird'); + $this->assertEquals('test query we>(ird', $q->getString()); + } + /** * Test setHandler() method *