PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] how can I do preg_replace?

 November 20, 2022     php, preg-replace     No comments   

Issue

I'm trying to get data from a site but there are some problems. I want to change the expression begining with <div class="phraserec" and ending with </div></div> how can I do it?

$source = "<div class="gwblock" id="1936036"><div class="phraserec"bla bla...</div></div>"
$output = preg_replace('/'. preg_quote('<div class="phraserec" '.'(.*?)'.'</div></div>','/') .'/', '</div>' , $ll);

I wanted output;

<div class="gwblock" id="1936036"><div class="phraserec"bla bla...</div>

Solution

There's no reason to call preg_quote(), and it's preventing (.*?) from being treated as a pattern. And instead of putting the capture group just around .*?, you can put it around everything before the second </div>.

$output = preg_replace('#(<div class="phraserec".*?</div>)</div>#', '$1', $source);

preg_quote() is needed when you want to turn dynamic input into a literal value in a regular expression.



Answered By - Barmar
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing