Reputation: 86
How do you find and replace a string in html page using the native PHP DOM Parser?
Example string to find: "the <a href='site.com'>company</a> has been growing for the past 5 months";
The parent is a full HTML page for example and the immediate predecessor of that string can be a <div>
or <p>
for example..
There is no id or class to that element. Is it still possible to find and manipulate it ?
There is nothing to identify the string or its immediate predecessor. Only the exact string, i.e. sequence of characters that the $search_string consists of.
Thanks!
EDIT:
$string_to_replace = "the <a href='site.com'>company</a> has been growing for the past 5 months";
$replacement_string = "<span class='someClass'>the <a href='site.com'>company</a> has been growing for the past 5 months";</span>
Upvotes: 1
Views: 1033
Reputation: 1601
Since this seems to span part of a node with child nodes, I would use a replace like this:
// Text in $html
$find = "the <a href='site.com'>company</a> has been growing for the past 5 months";
$find_len = strlen( $find );
$start = strpos( $html, $find );
if ( $start !== false ) {
$html = substr( $html, 0, $start )
. '<span class="someClass">' . $find . '</span>'
. substr( $html, $start + $find_len );
}
I do not have time to test it properly, but it might point you in the right direction.
PHP DOM would be excellent to change the href attribute of element a
or it's contents (company). It should also work if $find is the full contents of a <div>
-element
Upvotes: 1