Question

$details = "text...[book=123]...text...";

$details = preg_replace_callback(
  "/\[book=(.+?)\]/smi",
  function ($m) {
      global $skip_books;
      $book = $m[1];  // 123
      $feed = $m[2];  // 456       
  return "<div id=\"view_book_".$book."_".$feed."\"></div>";
  },
  $details
);

With this pattern i can only get $book ($m[1]):

"/\[book=(.+?)\]/smi"`

But i want to get $feed ($m[2]) too, so i replace to this [book=123_456].

How to get "456" ($m[2]) after the underline?

"/\[book=(.+?)_(.+?)\]/smi" ???
Was it helpful?

Solution

Don't use global here; you're already using a closure, so use the use:

function ($m) use ($skip_books) {
    // ...
}

Btw, you're not actually using $skip_books in the code you've shown so far, but I'm assuming that's because you've simplified it

If your arguments are always numbers, don't use something generic like (.+?) but be specific (the more the better):

/\[book=(\d+)_(\d+)\]/i

I've also removed the /s and /m modifiers, which are useless here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top