I have html code in a variable. For example $html
equals:
<div title="Cool stuff" alt="Cool stuff"><a title="another stuff">......</a></div>
I need to replace content of all title attributes title="Cool stuff"
and title="anot stuff"
and so on with title="$newTitle"
.
Is there any non-regex way to do this?
And if I have to use regex is there a better(performance-wise) and/or more elegant solution than what I came up with?
$html = '...'
$newTitle = 'My new title';
$matches = [];
preg_match_all(
'/title=(\"|\')([^\"\']{1,})(\"|\')/',
$html,
$matches
);
$attributeTitleValues = $matches[2];
foreach ($attributeTitleValues as $title)
{
$html = str_replace("title='{$title}'", "title='{$newTitle}'", $html);
$html = str_replace("title=\"{$title}\"", "title=\"{$newTitle}\"", $html);
}