How to apply str_replace only in identical terms?

Asked

Viewed 52 times

-1

I created the function below:

function setFamiliarURLsInsteadOfNames($FamURLsList=array(), $texto){
    if(!is_array($FamURLsList) || empty($FamURLsList))
        return array('error'=>true,'message'=>'$FamURLsList deve conter uma lista válida de Nomes e URLs');
    /* $FamURLsList é um array com os Nomes e URLs para a função abaixo */
    $toSearch = array(); $toChange = array();
    foreach($FamURLsList as $uriData){
        $toSearch[] = htmlentities($uriData["nome"]); /* Array com os Nomes */
        $toChange[] = '@'.$uriData["url"]; /* Array com os @URLs */
    }
    return str_ireplace($toSearch, $toChange, $texto);
}

Let’s suppose my array $FamURLsList, which will be passed in the function above, be the following:

$FamURLsList = array(
    0 => array(
        'url' => 'array-url-1',
        'nome' => 'fico'
    )
);

Suppose I now have the variable @texto with the value 'fico'. So I apply the function to this variable and I see the result:

echo setFamiliarURLsInsteadOfNames($FamURLsList,$texto);
/* Exibe: @array-url-1 no lugar de 'fico' */

However, if my variable @texto had the value 'identifico', the exit would be identi@array-url-1.

How can I replace only words that are exactly equal to the term searched, ignoring any other cases where it appears at the beginning, middle or end?

To try to make it even clearer, how can I just replace fico for @array-url-1 and never replace identifico for identi@url-array-1 or ficou for @array-url-1u?

  • I didn’t get it right: do you want to return a string function? What if the array $FamURLsList has more than one subarray?

  • 1

    Blz... you could use one if checking whether the text in the array is equal to the text sent. But beware of Boundary \b regex, because in some situations it may fail.

  • Yes, it is to return a string. It works like this: the $Famurlslist array has sub-arrays. Within each sub-array, you will have a combination of "name" and "url" keys. The "name"’s are searched in @text and replaced by the "url"’s, regardless of the number of sub-arrays. If you have more than 1 sub-array, you will overwrite them all by following the same rules. I managed to do almost perfectly using the boy’s tip below, with regular expression. There was a rule of regex that I didn’t know and already partially solved me :)

  • I found some situations where he failed, but just having this solution I can continue researching and learning on my own from now on. I needed more of a north even as I had tried everything and had not yet managed.

  • The function uses the sub-arrays to assemble the search and replace terms only. Each sub-array has one "nome" and a "url", that are iterated in foreach to generate two new arrays: one with the search terms called $toSearch and another with the terms that will be put in the place of the ancient called $toChange. These two arrays are passed in replace together, to do the sequential search and change. I could do it all in a loop loop, but so it consumes less resources. It’s a heavy system. You can see an example working here, if you want.

  • And in this webservice here is mounted the array $FamURLsList

  • And if you can’t find the word, which string should return?

  • Exactly the original, without any modification. The only thing I do there, actually, is to assemble two arrays with the searches and replacements, the return who makes is the function str_ireplace or, now with the modification, preg_replace. Both when no change, return the original string.

Show 3 more comments

1 answer

2


Hello,

In the example you passed it is possible to use regex to exclusively replace the word 'fico' as follows:

preg_replace('/\bfico\b/', '@array-url-1', $texto);

And in your code it would be:

return preg_replace('/\b'.$toSearch.'\b/', $toChange, $texto);

For more information on b read Word Boundaries

  • It worked almost perfectly the way you put it up there. But in some cases the \b failed. To be more specific, I could show you clear examples of what happened in operation (in the "Description" section of the page). Here a 100% functional text, changing the name to @URL and here a functional nothing. I’ll dig deeper into the Word Boundaries and see if I can fix it, but until then I can consider this code to be functional.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.