PHP | DOMCharacterData replaceData() Function

The DOMCharacterData::replaceData() function is an inbuilt function in PHP which is used to replace a substring within the DOMCharacterData node.

Syntax:

void DOMCharacterData::replaceData( int $offset, int $count, string $data)

Parameters: This function accept three parameters as mentioned above and described below:

  • $offset: It specifies the starting position to delete the data.
  • $count: It specifies the number of characters to delete.
  • $data: It specifies the string with which the range must be replaced.

Return Value: This function does not return any value.

Exceptions: DOM_INDEX_SIZE_ERR is raised if $offset is negative or greater than the number of 16-bit units in data, or if $count is negative.



Below given programs illustrate the DOMCharacterData::replaceData() function in PHP:

Program 1 (Replacing Data from beginning):

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOM Document
$dom = new DOMDocument('1.0', 'iso-8859-1');
  
// Create a div element
$element = $dom->appendChild(new DOMElement('div'));
  
// Create a DOMCdataSection
$text = $element->appendChild(
        new DOMCdataSection('My DOM Characters'));
  
// Replace the data
$text->replaceData(0, 2, 'My Replaced');
  
echo $dom->saveXML();
?>

chevron_right


Output:

<?xml version="1.0" encoding="iso-8859-1"?>
<div><![CDATA[My Replaced DOM Characters]]></div>

Use Chrome Developer tools to view the HTML or press Ctrl+U

Program 2 (Replacing Data in the middle):

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOM Document
$dom = new DOMDocument('1.0', 'iso-8859-1');
  
// Create a div element
$element = $dom->appendChild(new DOMElement('div'));
  
// Create a DOMCdataSection 
$text = $element->appendChild(
        new DOMCdataSection('GeeksErrorGeeks'));
  
// Replace Data
$text->replaceData(5, 5, 'For');
  
echo $dom->saveXML();
?>

chevron_right


Output:

<?xml version="1.0" encoding="iso-8859-1"?>
<div><![CDATA[GeeksForGeeks]]></div>

Reference: https://www.php.net/manual/en/domcharacterdata.replacedata.php




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.