php - 如何从数据库中查找字符串中的文本?

Let's say i have:

$title = "Rihanna - Man Down";

and a database multiple rows including one with a field called "name" with the "Rihanna" value

now... how can i check if in $title exists "Rihanna" and if it does how to add a link on "Rihanna" like this:

with other words check if one of the expresions from $title exists the database

  • i think this second formulation it is better
<a href="artist?id=Rihanna">Rihanna</a> - Man Down

I want to do something like youtube does at some of it;s music videos to be more clear

$words = explode("-", $title);
$result = array();

foreach ($words as $word)
{
    $word = trim($word);
    $res = mysql_query("SELECT name FROM table WHERE name='" . mysql_real_escape_string($word) . "'");

    if (mysql_num_rows($res) > 0)
    {
        $result[] = '<a href="artist?id=' . $word . '">' . $word . '</a>';
    }
    else
    {
        $result[] = $word;
    }
}

$result = implode($result, " - ");

This will however also link to "artist?id=Pink" if a song from another artist is named Pink, but you have the artist Pink in your database.

If I understood correct, this can do the work:

Then first search in DataBase, your query must be something like this:

//Search for word in DataBase on filed "name"

$title = "Rihanna - Man Down";
$arr = explode('-', $title); 
$title = $arr[0];

$result = mysql_query("SELECT name FROM table WHERE name LIKE '%" . mysql_real_escape_string($title) . "%'");

//If find results, then we replace and generate links in this loop

while($row = mysql_fetch_array( $result )) {
    $str = str_replace($title, '<a href="artist?id='.$title.'">'.$title.'</a>', $row['name']);
    echo $str; //<a href="artist?id=Rihanna">Rihanna</a> - Man Down
}

Split your title into words, and for each word check if your database contains row with that name. If yes, replace occurences of the word with link.

foreach (preg_split("/\s+/", $title) as $word) {
    if (word_in_database($word)) {
        $title = str_replace($word, "<a href=\"artist?id=$word\">$word</a>", $title);
    }
}