MySQL - confusing RegEx variable issue

I need help with RegEx. The concept is simple, but the actual solution far surpasses everything that I know how to understand. If someone could explain how I could achieve the desired effect (and give an explanation with any code example), that would be very helpful!


Basically, imagine a database table that stores the following row:

'My name is $1. I wonder who $2 is.'

First, keep in mind that the dollar sign format IS is set in stone. This is not just for this example - how these templates will actually be saved. I would like the next thread to return to the next line.

'My name is John. I wonder who Sarah is.'

How to create a query that searches with wildcards in this format and then returns the corresponding rows? I guess the correct expression would be the best way. Keep in mind that theoretically any number of wildcards should be acceptable.

Right now, this is part of my existing query that is dragging content from the database. Concatenation etc. Exists because there are several rows concatenated by a vertical bar in one database cell.

AND CONCAT('|', content, '|')
    LIKE CONCAT('%|', '" . mysql_real_escape_string($in) . "', '|%')

I need to change this line to work with variables that are part of the query, while maintaining the current effect (vertical bars, etc.). If RegEx also considers strips, the CONCAT () functions can be removed.

Here is an example of a string with concatenation that might appear in a database:

Hello, my name is $1.|Hello, I'm $1.|$1 is my name!

, , . $1 . .

+3
4

MySQL , . Regexp "(\ $) (\ d +)". , :

SELECT * FROM posts WHERE content REGEXP '(\\$)(\\d+)';

:

function ParseData($query,$data) {
    $matches=array();
    while(preg_match("/(\\$)(\\d+)/",$query,$matches)) {
        if (array_key_exists(substr($matches[0],1),$data))
            $query=str_replace($matches[0],"'".mysql_real_escape_string($data[substr($matches[0],1)])."'",$query);
        else
            $query=str_replace($matches[0],"''",$query);
    }
    return $query;
}

:

$query="$1 went to $2 house";
$data=array(
    '1' => 'Bob',
    '2' => 'Joe'
);
echo ParseData($query,$data); //Returns "Bob went to Joe house
+2

$1 $2 , :

http://php.net/manual/en/function.sprintf.php

.

<?php
$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
printf($format, $num, $location);
?>
0

, LIKE:

SELECT statement FROM myTable WHERE statement LIKE '%$1%'

, $1. , $1 - , , .

PHP . , - :

$count = 1;
while (strpos($statement, "$" . $count)) {
    $statement = str_replace("$" . $count, $array[$count], $statement);
}

( , , , .)

The only drawback is that it will fail if more than ten parameters are replaced on your line. The first walk will replace the first two characters at $ 10 as he searches for $ 1.

0
source

All Articles