I have a next string:
$str = '<h2 id="name of header">Name of header</h2>';
Need to replace all spaces in ID attribute. Example:
$str = '<h2 id="name-of-header">Name of header</h2>';
IS there any way I can do that?
I have a next string:
$str = '<h2 id="name of header">Name of header</h2>';
Need to replace all spaces in ID attribute. Example:
$str = '<h2 id="name-of-header">Name of header</h2>';
IS there any way I can do that?
<?php
$str = '<h2 id="name of header">Name of header</h2>';
$new_str = preg_replace_callback('#\"([^"]*)\"#', function($m){
return('"'. str_replace(' ', '-', $m[1]) .'"');
}, $str);
echo $new_str;
?>
It will work perfectly thanks
You could use a preg_replace to replace only the part you want to replace within your string.
You could also use str_replace but then, you have to select ONLY the part you want to replace.
With preg_replace you could do something like:
<?php
$str = '<h2 id="name of header">Name of header</h2>';;
$new_str = preg_replace(
'id="([\w\s]+)"',
'id="' . str_replace(' ', '-', $1) . '"',
$str);
?>
Where id="([\w\s]+)" would select only the ID part, and str_replace(' ', '-', "$1") would replace the spaces in it with a '-'.
But if you are not familiar with regex, I suggest you use gavgrif solution that is simpler.
Since the id is the only portion between quotes - explode it at the quotes - use str_replace to replace the spaces in the middle portion (the id part) and then join them back up to a single string.
this will mean that ...explode('"',$str); will give you the results of:
$str_portions[0] = <h2 id=
$str_portions[1] = name of header
$str_portions[2] = >Name of header</h2>;
str_replace the spaces with hyphens in the $str_portions[1] using str_replace(' ', '-', $str_portions[1]); will give:
$str_portions[1] = name-of-header
so the following is:
$str = '<h2 id="name of header">Name of header</h2>';
$str_portions = explode('"',$str); // splits the original statement into 3 parts
$str_id = str_replace(' ', '-', $str_portions[1]); // replaces the spaces with hyphens in the 2nd (id) portion
$str = $str_portions[0] . '"' . $str_id . '"' . $str_portions[2]; // joins all 3 parts into a single string again - reinserting the quotes
echo $str; // gives '<h2 id="name-of-header">Name of header</h2>';