1

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?

3
  • 1
    Question title does not match question body at all Commented Jan 15, 2017 at 9:15
  • Possible duplicate of Using PHP Replace SPACES in URLS with %20 Commented Jan 15, 2017 at 9:23
  • So what have you tried? Commented Jan 15, 2017 at 9:59

3 Answers 3

0
<?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

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, it should work. But I have a string <h2 id="name of header">Name of header</h2> . So It replace all spaces in this string.
You need to set interval start on id index and end with > index
Pretty and simple. Thank you very much
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.