19
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【PHP】正規表現で置換するpreg_replace【サンプルコード付き】

Last updated at Posted at 2018-05-04

はじめに

プライベートでLaravelを勉強しています。
PHPを完全に習得している訳ではないので、ちょくちょく調べ物をしながら進んでいます。
調べたものをアウトプットしたいので、備忘録として残しておきます。

preg_replaceを使う

結論から言うと、下記のような使い方です。

preg_replace($正規表現パターン, $置換後の文字列, $置換対象)

## 例として書いてみた サンプルだけ見てわかった気になると危ないので、例として書き換えてみました。 h1タグをaタグに置換するコードです。
substitution.php
<?php

$str = '<h1>Google.com</h1>へのリンクです';
$pattern = '/<h1>(.*)<\/h1>/u';
$replace = '<a href="http://$1">$1</a>';

$content = preg_replace($pattern, $replace, $str);

echo $content;

?>

結果はこんな感じです。

Google.comへのリンクです

感想

preg_replace()というより、正規表現に苦戦しました。
がっつり正規表現を使った経験がないので、取り組むたいです。

参考

19
15
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?