Home>

The following HTML is output by the following PHP.
This time we want to change this output further and output it as HTML at the bottom.

<? php
function reply () {
  $Content = '<p><span>Hello<a href = "#">@ hanako</a>I<span>It is a good night.</p>';
  if (preg_match ('/<span>(.*?)<\/span>/i', $content, $matches)) {
    return $matches [1];
  }
};?>
<? php echo '<p>'. reply (). '</p>';?>

↓ Output HTML

<p>Hello<a href = "#">@ hanako</a>I</p>

↓ Target HTML

<p>Hello<a href = "#">@<span>hanako</span></a>I</p>


I can't figure out how to create a single span like the target HTML.
I am very sorry for the round throwing posture, but could someone please show me the way ...

php
  • Answer # 1

    How about this?

    <? php
    function reply () {
      $Content = '<p><span>Hello<a href = "#">@ hanako</a>I</span>It is a good night.</p>';
      if (preg_match ('/<span>([^<] +<a [^>] +>@) ([^<] +)<\/a>/i', $content , $matches)) {
        return "{$matches [1]}<span id = \" name \ ">{$matches [2]}</span></a>";
      }
    };?>
    <? php echo '<p>'. reply (). '</p>';?>

  • Answer # 2

    Depending on how much accuracy is required, but redundant If all you need to do is fit

    $content = '<p><span>Hello<a href = "#">@ hanako</a>I</span>good night is not it.</p>';
    $pattern = '/ (<p>. *?)<span>(. *?<a [^>] *?>@) (. +?) (<\/a>. * ) (<\/span>). *? (<\/p>)/';
    $replacement = "\\ 1 \\ 2<span id = \" name \ ">\\ 3 \\ 5 \\ 4 \\ 6";
    $content = preg_replace ($pattern, $replacement, $content);
    print htmlspecialchars ($content);