Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php find string with regex

Tags:

regex

php

I've read multiple tutorials on regex but it just won't stick in my head. I can never get my patterns to work. Hope someone can help.

I have a php variable ($content) where I need to find a certain pattern that looks like this

[gallery::name/of/the/folder/]

I would like to search:

- starting with "[gallery::" - any other character (variable length) - ending with "]" 

So far, in PHP I have:

   preg_match('/\[gallery\:/', $content, $matches, PREG_OFFSET_CAPTURE); 

I can find [gallery: but that's it. I would like to be able to find the rest (:name/of/the/folder/])

Any help is appreciated! Thanks!

like image 778
VVV Avatar asked Apr 13 '12 14:04

VVV


People also ask

How do you check if a string matches a regex in PHP?

Matching a string In PHP, you can use the preg_match() function to test whether a regular expression matches a specific string. Note that this function stops after the first match, so this is best suited for testing a regular expression more than extracting data.

How do I match a string in PHP?

The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().

What does Preg_match mean in PHP?

preg_match() in PHP – this function is used to perform pattern matching in PHP on a string. It returns true if a match is found and false if a match is not found. preg_split() in PHP – this function is used to perform a pattern match on a string and then split the results into a numeric array.

What is use of Preg_replace in PHP?

PHP | preg_replace() Function The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content.


2 Answers

Try capturing it:

preg_match("/\[gallery::(.*?)]/", $content, $m); 

Now $m is an array:

0 => [gallery::/name/of/the/folder/] 1 => /name/of/the/folder/ 
like image 114
Niet the Dark Absol Avatar answered Sep 23 '22 16:09

Niet the Dark Absol


change your regex to

'/\[gallery::([A-Za-z\/]+)\]/' 

Since I put the folder/path part in parenthesis, you should get a capture group out of it.

like image 20
Tim Hoolihan Avatar answered Sep 24 '22 16:09

Tim Hoolihan