1

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>

3
  • Which string do you want to replace with what? Commented Nov 12, 2015 at 22:27
  • In the example above, you do not search for the contents of a DOM element, but rather a text string. If you want to modify <a href ... </a> you could use PHP DOM, but not to search for "the <a href='site.com'>company</a> has been growing for the past 5 months". Use a string search/replace for that or a regexp search/replace Commented Nov 12, 2015 at 22:31
  • Please see the EDIT. Thanks for clarifying. I've been trying to use str_replace() with little success. Also, people say you should not parse html with regex(which is needed for some replacements). Can you please have a look at this question I posted: stackoverflow.com/questions/33671497/… Commented Nov 12, 2015 at 22:36

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.