Reputation: 3076
Here's the situation:
Everithing starts form and array and string:
$var = 'This is a string';
$arr = array(
'This' => '<strong title="this is string">This</strong>',
'is' => '<strong title="this is string">is</strong>'
);
If i do a simple str_replace to replace the key with the value in $var, you can pretty much guess it will replace even inside the title, what I want is $var in the end to be this:
<strong title="this is string">This</strong> <strong title="this is string">is</strong> a string
Can I use a simple regex? DomDoc? or it's simply a complicated algorithm?
Upvotes: 0
Views: 46
Reputation: 3701
If whitespace (this will replace multiple whitespace with a single space) is not important to you, you may use strtok
to split the string and do replacements on each word/token:
$var = 'This is a string';
$arr = array(
'This' => '<strong title="this is string">This</strong>',
'is' => '<strong title="this is string">is</strong>'
);
$tok = strtok($var, " \n\t"); // Split on space, newline and tab
$result = array();
while ($tok !== false) {
if (isset($arr[$tok])) {
$result[] = $arr[$tok];
}
else {
$result[] = $tok;
}
$tok = strtok(" \n\t");
}
echo implode(' ', $result), PHP_EOL;
Output:
<strong title="this is string">This</strong> <strong title="this is string">is</strong> a string
Upvotes: 0
Reputation: 7785
in clean way, hope that helps :)
<?php
define ("START_TAG", '<strong title="this is string">');
define ("END_TAG", '</strong>');
// 'i' is for case insensitive, you can remove it ...
$pattern = '#(this|is)#i';
var_dump (preg_replace ($pattern, START_TAG . '$1' . END_TAG, 'This is test'));
Upvotes: 1