Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression to get sub string via php

How can I use a regular expression in the substr() PHP function to get a substring matched by a pattern?

Edited:

example:

$name = 'hello [*kitty*],how good is today';

I want to get what is between [....] placeholder.

like image 640
hd. Avatar asked Feb 14 '11 11:02

hd.


Video Answer


2 Answers

substr() only matches whole strings. You are looking for preg_match().

Update:

$name = 'hello [*kitty*],how good is today';
preg_match( '/\[(.*?)\]/', $name, $match );
var_dump( $match );

You can find the name in $match[1]. I suggest you read up on regular expressions to understand preg_match().

like image 169
Tim Avatar answered Oct 15 '22 18:10

Tim


Try this:

$matches = array();
preg_match("/\[([^]]*)\]/", 'hello [*kitty*],how good is today', $matches);
print_r($matches);

Oops, fixed it now :)

like image 41
Mārtiņš Briedis Avatar answered Oct 15 '22 19:10

Mārtiņš Briedis