1

I have just started using a database on my local drive. I would like to know how I would use a regex commands to search the data in my database.

PS: I am a beginner, I have just started coding since last week.

My code so far:

<?php
error_reporting(0);
session_start(oid);
    require 'view/header.php';
?>

<?php

?>

<form action="" method="post">
    <h4>Insert a regex command below</h4>
    Regex: <input type="text" name="regex"/>
    <input type="submit" value="Search"/><br/><br/>
</form>

<?php
    $regex=$_POST["regex"];

    if(!empty("regex")) { 
        if(preg_match($regex, "Hello, my name is Hasan!")) {
            echo "That is correct";
        } else {
            echo "That is incorrect";
        }
    }
?>

<?php
    require 'view/footer.php';
?>

Any feedback is welcome. I am in the beginning stages of learning this.

3
  • 1
    i don't get it, you want to search database or search the result after you get it from database? Commented Jun 24, 2015 at 15:16
  • MySQL supports (basic) regex. That said, there are plenty of tutorials available about fetching data from a db with PHP. I strongly suggest you sanitize user input, and use PDO or some other DB library for querying your database. Commented Jun 24, 2015 at 15:16
  • @Prashank I want to search the database. The database is filled with different documents and I want to use regex to search through those documents and provide an output. For now, the user will have to manually input the regex commands. Commented Jun 24, 2015 at 15:26

3 Answers 3

4

you can just use REGEXP in the query. have a look a this resource which contains all the detail you need.

syntax is simple as follows

$qry = "select * from aTable where someName REGEXP '$pattern'";
Sign up to request clarification or add additional context in comments.

Comments

3

Since you are using MySQL, you can use a MySQL's regular expression support which includes both REGEXP and NOT_REGEXP operators. Here's some information from MySQL:

MySQL uses Henry Spencer's implementation of regular expressions, which is aimed at conformance with POSIX 1003.2. MySQL uses the extended version to support pattern-matching operations performed with the REGEXP operator in SQL statements.

More information is on the MySQL Reference Manual section on Regular Expressions.

Comments

0

You can either return all the rows from the database first and then filter through all the rows in PHP. OR you can directly filter the query using MySQL syntax. Heres a resource on MySQL regular expressions - http://java.dzone.com/articles/mysql-regexp-regular Hope this helps!

Comments

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.