简体   繁体   English

如何替换字符串中的所有空格但仅在ID属性中?

[英]How to replace all spaces in string but only in ID attribute?

I have a next string: 我有一个下一个字符串:

$str = '<h2 id="name of header">Name of header</h2>';

Need to replace all spaces in ID attribute. 需要替换ID属性中的所有空格。 Example: 例:

$str = '<h2 id="name-of-header">Name of header</h2>';

IS there any way I can do that? 有什么方法可以做到吗?

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. 由于id是引号之间的唯一部分 - 在引号处将其展开 - 使用str_replace替换中间部分(id部分)中的空格,然后将它们连接回单个字符串。

this will mean that ...explode('"',$str); will give you the results of: 这意味着...... explode('“',$ str);会给你以下结果:

$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]); 使用str_replace('',' - ',$ str_portions [1])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>';
<?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. 您可以使用preg_replace仅替换字符串中要替换的部分。

You could also use str_replace but then, you have to select ONLY the part you want to replace. 您也可以使用str_replace但是,您必须仅选择要替换的部分。

With preg_replace you could do something like: 使用preg_replace,您可以执行以下操作:

<?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 '-'. 其中id="([\\w\\s]+)"将仅选择ID部分,而str_replace(' ', '-', "$1")将用' - '替换其中的空格。

But if you are not familiar with regex, I suggest you use gavgrif solution that is simpler. 但是如果你不熟悉正则表达式,我建议你使用更简单的gavgrif解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM