Manatok
Manatok

Reputation: 5696

PHP escaping delimiter

I am using PHPs' strtr method to replace certain tokens/placeholders in a string. This works very well but now I'm trying to work out if all of my tokens were replaced.

The following example:

$trans = array(":hello" => "hi", ":hi" => "hello");
echo strtr(":hi all, I said :hello", $trans);

will output:

hello all, I said hi

Both tokens were replaced successfully but how do I check this. I can't search the output for occurrences of my delimiter ':' since the output string could contain valid ':' in the data.

Is there a way that I can escape these delimiters before doing the replace, then do a count on the unescaped delimiters to see if there were any token left unreplaced, and then finally unescape the escaped delimiters before returning?

NOTE: I cannot use str_replace, this method needs to be used.

Upvotes: 0

Views: 241

Answers (1)

deceze
deceze

Reputation: 522005

I don't think strtr can help you here, it just replaces whatever it finds. What you seem to want is to figure out if there is a difference between the tokens in the array and in the string. For that, something like this should do:

preg_match_all('/:\w+/', $str, $matches);
if (array_diff($matches[0], array_keys($trans))) {
    // the string has tokens that aren't in $trans
}

Upvotes: 1

Related Questions