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?

  • Browser and eat with spaces. And it was necessary to replace earlier. - Qwertiy ♦
  • I do not need a browser. Why write empty tips? - Anton
  • Why not write them? I am not responsible to write it. - Qwertiy ♦
  • Indeed, what is the ultimate goal and where does the source line come from? - Gedweb
  • Initially, there is just a <h2> Name of header </ h2> tag. With the help of preg_replace, an ID is substituted for this tag with its contents. The goal is to replace all spaces in the id parameter with - - Anton

3 answers 3

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> 
  • Thank. I already use the exact same solution =) Of course, this method is much better than which I suggested earlier. - Anton

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; // Π²Ρ‹Π²ΠΎΠ΄ΠΈΠΌ Π³ΠΎΡ‚ΠΎΠ²Ρ‹ΠΉ ΠΊΠΎΠ½Ρ‚Π΅Π½Ρ‚ } 
  • one
    it's stuffing, not a solution - Gedweb
  • This solves my problem. Especially since there are no other options here - Anton
  • all this can be solved with one regular expression. Constructions of the form (.*.) Are meaningless, I hope you will understand why. - Gedweb
  • Is there an example of at least one? - Anton

I would use str_relace

$str = '<h2 id="name of header">Name of header</h2>'; $str = str_replace(" ", "-", $str); echo $str;

  • this will replace the entire line, in the end it will be <h2-d = "name-of-header"> Name-of-header </ h2> I need only in the ID - Anton