0

I'm trying to find a string inside curly braces that can appear in many variations.

i.e. In the following string i'm searching for the word Link

asdasd{Link1111:TAG}\r\n {TAG:Link2sds}

I'm using the following command: $pattern = "/{(Link.*?)}|{(.*Link.*?)}/";

and the result is:

{array} [3]
 0 => {array} [2]
     0 = "{Link1:TAG}"
     1 = "{TAG:Link2}"
 1 = {array} [2]
     0 = "Link1:TAG"
     1 = ""
 2 = {array} [2]
     0 = ""
     1 = "TAG:Link2"

I'm expecting only the first array without the curly braces...what am i missing with the regex? thx.

2
  • 1
    Just use $pattern = "/{(.*?Link.*?)}/"; and print_r($matches[1]); Commented May 17, 2016 at 17:52
  • yeap! spot on...if you want to submit it as an answer so i can accept it :) Commented May 17, 2016 at 17:56

2 Answers 2

1

preg_match_all is global and finds all matches. If you want to find it just once use preg_match.

Demo: https://eval.in/572825

The 0 index in your current example is all matches. The 1 is the first capture group Link.*?, and the 2 is your second capture group .*Link.*?.

Sign up to request clarification or add additional context in comments.

Comments

0

Just use /{(.*?Link.*?)}/ and your matches will be in index 1

<?php

$str = "asdasd{Link1111:TAG}\r\n {TAG:Link2sds}";

$pattern = "/{(.*?Link.*?)}/";
preg_match_all($pattern, $str, $matches);

print_r($matches[1]);

Your eval

1 Comment

Wrong! You can't use .*? before Link. Consider the string {toto123:tag} {Link111:tag}. Remember that the regex engine walks from left to right and try to succeed at each position.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.