2

I have a filter hook that passes a string of HTML. An example string might be:

'<input type="text" value="4893" />'

The string is passed to the filter hook:

add_filter( 'html_filter', 'my_html_filter', 10, 1 );
function my_html_filter( $html ) {

    $html =     <--- REPLACE VALUE ATTRIBUTE HERE

    return $html;
}

What I need to do inside of my_html_filter() is replace the value of value="" and I'm not sure how to isolate this in $html. As a random example, say $html is passed as:

'<input type="text" value="345" />'

and I need to change it to:

'<input type="text" value="14972" />'

How would I do this? A combination of str_replace and a regex expression?

2
  • This will probably work, however using regex on html is never a very good idea. There might be some other hook that just replaces the value only, can you please share what value we are talking about? Commented Mar 10, 2017 at 19:15
  • eval.in/752568 Commented Mar 10, 2017 at 19:26

2 Answers 2

5

Use an HTML parser to parse HTML!

$html = '<input type="text" value="4893" />';
$dom = new DomDocument;
$dom->loadHTML($html);
$nodes = $dom->getElementsByTagName('input');
$node = $nodes[0];
$node->setAttribute('value', 'foo');
echo $dom->saveHTML($node);

Result:

<input type="text" value="foo">
Sign up to request clarification or add additional context in comments.

Comments

0
add_filter( 'html_filter', 'my_html_filter', 10, 1 );
function my_html_filter( $html ) {

    // assuming you have a way to know the new value you want
    // i used an example value, probably you have to construct 
    // the following string
    $new_value = 'value="65432"';

    $html = preg_replace('/value="[0-9]+"/', $new_value, $html);

    return $html;
}

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.