rwkiii
rwkiii

Reputation: 5846

Replace attribute value in an HTML string using PHP

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?

Upvotes: 2

Views: 2188

Answers (2)

miken32
miken32

Reputation: 42716

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">

Upvotes: 5

nikos.svnk
nikos.svnk

Reputation: 1375

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;
}

Upvotes: 0

Related Questions