Danny Valariola
Danny Valariola

Reputation: 1118

php regex find part of string

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.

Upvotes: 0

Views: 85

Answers (2)

Thamilhan
Thamilhan

Reputation: 13293

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

Upvotes: 0

chris85
chris85

Reputation: 23892

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.*?.

Upvotes: 1

Related Questions