Sign in to follow this  

PHP preg_replace .*?

This topic is 4537 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey everyone. I would like to know how to use preg_replace to make it return anything in between
<!-- DESC --> ..some words and <!-- /DESC -->
. Like for example I have a document and it contains
<!-- DESC -->Welcome, this is a test <!-- /DESC -->
I want my function to return Welcome, this is a test. How would I do this? Thanks in advance.

Share this post


Link to post
Share on other sites
Alright. I'll show you with single strings since that's the simplest. It's not hard to extend it to using arrays for the search string and the replace string.


// I assume you're getting your string from a file. It doesnt really matter
$f = fopen('your_file', 'r');
$text = fread($f, filesize('your_file'));

// What this does is searches for the entire block for your DESC tag
// The inside of the block is put in parentheses so that I can backreference
// it in the replacement. The $1 is the reference to everything in the parentheses
$new_text = preg_replace('/<!-- DESC -->(.*)<!-- \/DESC -->/', '$1', $text);

Share this post


Link to post
Share on other sites

This topic is 4537 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this