开发者

How can I stop str_replace replacing only part of a filename?

开发者 https://www.devze.com 2023-03-19 13:38 出处:网络
I\'m going through an HTML file replacing all the references to external files with new ones, however, sometimes this results in errors.

I'm going through an HTML file replacing all the references to external files with new ones, however, sometimes this results in errors.

For example: I want to replace all instances of styles.css with 1.css and all instances of iestyles.css with 2.css in this source code:

<html>
  <link href="styles.css" />
  <link href="iestyles.css" />
</html>

Once I've run str_replace("styles.css"开发者_StackOverflow, "1.css", $html); the source code looks like this:

<html>
  <link href="1.css" />
  <link href="ie1.css" />
</html>

So when I run the second query, it doesn't change the iestyles.css reference because it no longer exists. Is there a way around this? I guess I could invent an elaborate regular expression, but there are a lot of variables to consider because not all code is well formed.

Cheers


Just change the order: First replace iestyles.css with 2.css and then replace styles.css with 1.css.

If you are sure the filename is the only thing within the href-attribut, you could also include the double quotes "

$html = str_replace('"styles.css"', '"1.css"', $html);
$html = str_replace('"iestyles.css"', '"2.css"', $html);


Including the double quotes (assuming they all use double quotes) should work.

str_replace('"styles.css"', '"1.css"', $html);


use preg_replace();

preg_replace('|<link href="styles\.css" />|', '1.css', $html);

or just prepend double quotes before styles

str_replace('"styles.css', '"1.css', $html);


Just include the quotes in your replacement.

replace "styles.css" with "1.css"


You could change 'iestyles.css' first.

0

精彩评论

暂无评论...
验证码 换一张
取 消