hd.
hd.

Reputation: 18306

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.

Upvotes: 13

Views: 40013

Answers (2)

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17762

Try this:

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

Oops, fixed it now :)

Upvotes: 4

Tim
Tim

Reputation: 14154

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().

Upvotes: 36

Related Questions