2

I want to search for a word+number if that SQL returns nothing, I will default it to a full LIKE search, is there any way to implement regex like this in SQL?

Example:

$queryWord = potato
  • It should first search for potato+somenumber up to 4 digits
  • It should return all matches with potato+somenumber
  • If that fails, it defaults to a full search with wildcards on both sides

Like this:

$sql = "SELECT * FROM `words` WHERE `searchWord` LIKE '$queryWord+number';";
$result = mysqli_query($con, $sql);

if (mysqli_num_rows($result) == 0) {

    $sql =  "SELECT * FROM `words` WHERE `searchWord` LIKE '%$queryWord%';"; // full search
    $result = mysqli_query($con, $sql);
    // etc etc

}

1 Answer 1

3

Just change your query to this:

$sql = "SELECT * FROM `words` WHERE `searchWord` REGEXP '$queryWord(\d{1,4})';";

and here is a Rubular that proves the Regex.

Sign up to request clarification or add additional context in comments.

1 Comment

Just to say, there are 2 keywords that can be used in MySQL for regular expression matching: REGEXP and RLIKE, they are the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.