简体   繁体   中英

PHP – preg_replace() for words in string (regex pattern difficulties)

I'm new to PHP & Arrays even though I read a lot of tutorials already. Please be understanding. :)

My intentions: For a fulltext search I'm trying to replace words within a string with custom other words contained in a list of words. It occurs to me that in order to get whole words rather than the found string as part of another word I have to use preg_replace() with a specific pattern instead of str_replace().

My problem: If a certain word is part of the list of words ie [apples], I'm trying to replace ie [Short text in a fulltext search] with ie [Short apples in a fulltext search]. Naturally the final string looks like [Short apples in a fullapples search] or I get some delimiter warnings.

So I'm trying to figure out a pattern for the preg_replace() function to only replace full words and not strings within combines words. And on top of that I'm pulling the word pairs out of an associative array to have a better overview of the list. This is where I'm a novice.

My trials:

$replacements = array(
                  'text' => 'apples',
                  etc…
                );

$pattern = '#\b'($searchterm)'\b#;
$searchterm = preg_replace(array_keys($replacements), $pattern, $searchterm);

echo $searchterm;

Thank you for your help!

strtr may be enough for this task. .

In order to replace full words and not strings within combines words, we simply can add blank to the head an to the end of the replace pair.

<?php
$replacements = array(
    'text' => 'apples',
);

$realRreplacements = array();
foreach ($replacements as $from => $to)
{
    $from = ' ' . $from . ' ';
    $to = ' ' . $to . ' ';
    $realRreplacements[$from] = $to;
}

$str = 'Short text in a fulltext search';
$str = strtr($str, $realRreplacements);
echo $str, "\n";
// output: Short apples in a fulltext search

-

                      ************ update *************

turn back to preg_replace :

<?php
$list = array(
    'text' => 'apples',
    'Short' => 'Long',
    'search' => 'find',
);
$pattens = array();
$replacement = array();
foreach ($list as $from => $to)
{
    $from = '/\b' . $from . '\b/';
    $pattens[] = $from;
    $replacement[] = $to;
}
$str = 'Short text in a fulltext search';
$str = preg_replace($pattens, $replacement, $str);
echo $str, "\n"; // Long apples in a fulltext find

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM