1

I have a string which contains:

[quote name="username" url="/t/44223/topics-name#post_734738"]

I want to write a php regex which will find all the occurrence of this string and find the post number (ex. 734738) and later replace the whole thing with:

[quote=username;new post number based on 734738]

Requirements:

  1. Only URL which starts with '/t/' and ends with '#post_{number}'.
  2. By 'new post number based on 734738' means this will be my custom post number which I will generate from database.

Please help me out. Thanks.

Final Answer:

This is the final answer in case anyone needs this :)

$string = '[quote name="user343I_nsdfdame" url="/t/44223/topics-name#post_734738"]What is your name?[/quote][quote name="username" url="/t/45454/topics-name#post_767676"]Test string[/quote]The quick brown fox....';

if(preg_match_all("/\[quote name=\"([^\"]*)\" url=\"\/t\/[^#]*#post_([0-9]*)\"\]/", $string, $matches)) {
    foreach ($matches[0] as $match) {
        if(preg_match("/\[quote name=\"([^\"]*)\" url=\"\/t\/[^#]*#post_([0-9]*)\"\]/",$match, $reg)) {
            $new = "[quote=".$reg[1].";".$reg[2]."]"; // I have changed $reg[2] according to my need.
            $string = str_replace($match, $new, $string);
        }   
    }
}

echo $string;

Output:

[quote=user343I_nsdfdame;734738]What is your name?[/quote][quote=username;767676]Test string[/quote]The quick brown fox....
4
  • 1
    Where's the code you've tried? Commented Aug 23, 2015 at 18:00
  • Actually I have zero knowledge about php regex. So I am hoping for someone to write me a regex. Commented Aug 23, 2015 at 18:03
  • 2
    Well you should at least make an effort to research it and try something before expecting someone to divy up their time writing your code for free. Commented Aug 23, 2015 at 18:04
  • Actually I was studying regex and honestly I am having fun. Really amazing thing. Sorry, next time I will study first and post question :) Commented Aug 23, 2015 at 18:25

1 Answer 1

2

This will do it:

$string = '[quote name="username" url="/t/44223/topics-name#post_734738"]';
$new = "";
if(preg_match("/\[quote name=\"([^\"]*)\" url=\"\/t\/[^#]*#post_([0-9]*)\"\]/",$string,$reg)) {
    $new = "[quote=".$reg[1].";new post number based on ".$reg[2]."]";
}
echo $new;

Output is:

[quote=username;new post number based on 734738]
Sign up to request clarification or add additional context in comments.

1 Comment

your coder is correct but for multiple occurrence I think I have to use 'preg_match_all' function. Anyway thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.