[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


php and preg replace

Posted on 2011-10-14
Medium Priority
Last Modified: 2012-06-21
Hi Experts,

Why does this add two << around the preg replace...

I just want to add strong to first para only

$text = preg_replace('<p>', '<p><strong>', $text, 1);
$text = preg_replace('</p>', '</strong></p>', $text, 1);

Question by:maccaj51
  • 2
  • 2
LVL 48

Accepted Solution

hernst42 earned 2000 total points
ID: 36967893
Wrong code, You miss the regexp delimiters. Try:

$text = preg_replace('#<p>#', '<p><strong>', $text, 1);
$text = preg_replace('#</p>#', '</strong></p>', $text, 1);

Open in new window

LVL 111

Expert Comment

by:Ray Paseur
ID: 36967996
Unlike ereg() that has been deprecated and will be removed, the PCRE expressions require a delimiter.  Certain pieces of information for the regex follow the trailing delimiter.  For example, you can make the expression case-insensitive by adding the letter "i" at the end, after the final delimiter.

You may also find that certain "meta characters" need to be escaped by prepending them with a backslash.  PHP is inconsistent in its application of this rule.  Enlightening reading here:

Author Comment

ID: 36968448
Hi Ray,

Thanks for the information. I would class myself a little above beginner so will have a look...

Is there any reason why i should accept and use hernst42 answer?
LVL 111

Expert Comment

by:Ray Paseur
ID: 36969298
Sure!  Just looking at it, I am fairly sure it works.  In some cases the wickets < and > may be treated as meta-characters, but this is not one of them.

Author Closing Comment

ID: 36969489
Many Thanks hernst42

& Ray!

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses four methods for overlaying images in a container on a web page
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses
Course of the Month20 days, 2 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question