There is a line:
$str = '<h2 id="name of header">Name of header</h2>'; I need to replace all spaces with the '-' character only in the ID parameter (id = "name of header"). How to do it?
Name of header'; I need to replace all spaces with t...">
There is a line:
$str = '<h2 id="name of header">Name of header</h2>'; I need to replace all spaces with the '-' character only in the ID parameter (id = "name of header"). How to do it?
use the preg_replace_callback function. For your example:
$str = '<h2 id="name of header">Name of header</h2><h3 id="name of header">Name of header</h3>'; $str = preg_replace_callback('/id="([^"]+)"/', function ($matches) { return 'id="'.str_replace(' ', '-', $matches[1]).'"'; },$str); echo $str; result:
<h2 id="name-of-header">Name of header</h2><h3 id="name-of-header">Name of header</h3> In general, if someone needs to do a similar task, here is the solution to my question:
$content = explode("\r\n", $content); //ΡΠ°Π·Π±ΠΈΠ²Π°Π΅ΠΌ ΠΊΠΎΠ½ΡΠ΅Π½Ρ Π½Π° ΡΡΡΠΎΠΊΠΈ foreach ($content as $str) { // ΠΏΠ΅ΡΠ΅Π±ΠΈΡΠ°Π΅ΠΌ ΠΏΠΎΠ»ΡΡΠ΅Π½Π½ΡΠ΅ ΠΌΠ°ΡΡΠΈΠ² if ( preg_match("/(<h. id=.*.)(>)(.*.)(<\/h.>)/", $str) == 1 ) { //Π΅ΡΠ»ΠΈ ΡΠ΅ΠΊΡΡΠ°Ρ ΡΡΡΠΎΠΊΠ° ΡΠΎΠ΄Π΅ΡΠΆΠΈΡ Π»ΡΠ±ΠΎΠΉ ΡΠ΅Π³ h1-h6 $id = preg_replace("/(<h. id=.*.)(>)(.*.)(<\/h.>)/", "$3", $str); // Π²ΡΠ±ΠΈΡΠ°Π΅ΠΌ ΡΠΎΠ»ΡΠΊΠΎ ΡΠΎ, ΡΡΠΎ Π»Π΅ΠΆΠΈΡ Π² id $bad_symbols = array(" ", ","); // Π·Π°Π΄Π°Π΅ΠΌ ΡΠΈΠΌΠ²ΠΎΠ»Ρ, ΠΊΠΎΡΠΎΡΡΠ΅ Π½Π΅ΠΎΠ±Ρ
ΠΎΠ΄ΠΈΠΌΠΎ Π·Π°ΠΌΠ΅Π½ΠΈΡΡ $id = trim(str_replace($bad_symbols, "-", $id)); //Π·Π°ΠΌΠ΅Π½ΡΠ΅ΠΌ Π½Π΅Π½ΡΠΆΠ½ΡΠ΅ ΡΠΈΠΌΠ²ΠΎΠ»Ρ ΠΏΡΠ΅Π΄Π²Π°ΡΠΈΡΠ΅Π»ΡΠ½ΠΎ ΡΠ΄Π°Π»ΠΈΠ² ΠΏΡΠΎΠ±Π΅Π»Ρ ΠΏΠΎΠ±ΠΎΠΊΠ°ΠΌ $str = preg_replace("/(<h. id=)(.*.)(>)(.*.)(<\/h.>)/", "$1'".$id."'$3$4$5", $str); // ΡΠΎΠ±ΠΈΡΠ°Π΅ΠΌ ΠΎΡΡΠΎΡΠΌΠ°ΡΠΈΡΠΎΠ²Π°Π½Π½ΡΡ ΡΡΡΠΎΠΊΡ } echo $str; // Π²ΡΠ²ΠΎΠ΄ΠΈΠΌ Π³ΠΎΡΠΎΠ²ΡΠΉ ΠΊΠΎΠ½ΡΠ΅Π½Ρ } (.*.) Are meaningless, I hope you will understand why. - GedwebI would use str_relace
$str = '<h2 id="name of header">Name of header</h2>'; $str = str_replace(" ", "-", $str); echo $str;
Source: https://ru.stackoverflow.com/questions/614653/
All Articles