1

I just need to check a string (php) for squared brackets. If there are squared bracket, I want to get it's content for further processing.

String:

This is just a
[needle]
example

As there is a squared bracket, I want to get it's value, which is "needle" in this example. Now I will get some value for needle in a SQL-DB and replace the bracket with that.

i.e. keyword "needle" will get the value "great" out of the DB, so the result would be:

This is just a
great
example

I tried to use str_replace

$content= str_replace('[]', '',$content);

but this is the wrong approach, as I first need to check for the value and send a SQL-query...

Update: I think the linked thread (Capturing text between square brackets in PHP) has a different question. As I don't just get the hits, but process these hits by replacing them. Therefore the mentioned function preg_replace_callback is the best solution.

Community
  • 1
  • 1
user3142695
  • 15,844
  • 47
  • 176
  • 332
  • 1
    The best function for this would be [preg_match_all()](http://www.php.net/manual/en/function.preg-match-all.php) - `preg_match_all("/\[(.*?)\]/m", $text, $matches);` – Mark Baker Aug 25 '14 at 16:54
  • 1
    http://stackoverflow.com/questions/10104473/capturing-text-between-square-brackets-in-php –  Aug 25 '14 at 16:55
  • 1
    And if you want to substitute their [content], `preg_replace_callback()` might be worth investigating too. – mario Aug 25 '14 at 17:07

1 Answers1

0

Use preg_match to find the word inside the []:

preg_match('/\[[^\]]+\]/', $content, $match);
print_r($match);

Then use $match[0] in your query. Then you can use preg_replace in the same manner.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87