LukeDS
LukeDS

Reputation: 141

preg_match how to return matches?

According to PHP manual "If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on."

How can I return a value from a string with only knowing the first few characters?

The string is dynamic and will always change whats inside, but the first four character will always be the same.

For example how could I return "Car" from this string "TmpsCar". The string will always have "Tmps" followed by something else.

From what I understand I can return using something like this

preg_match('/(Tmps+)/', $fieldName, $matches);

echo($matches[1]);

Should return "Car".

Upvotes: 1

Views: 3554

Answers (5)

Philipp
Philipp

Reputation: 15629

Given that the text you are looking in, contains more than just a string, starting with Tmps, you might look for the \w+ pattern, which matches any "word" char.

This would result in such an regular expression:

/Tmps(\w+)/

and altogether in php

$text = "This TmpsCars is a test";
if (preg_match('/Tmps(\w+)/', $text, $m)) {
    echo "Found:" . $m[1]; // this would return Cars
}

Upvotes: -1

executable
executable

Reputation: 3600

An alternative way is using the explode function

$fieldName= "TmpsCar";
$matches = explode("Tmps", $fieldName);
if(isset($matches[1])){
    echo $matches[1]; // return "Car"
}

Upvotes: 0

Don't Panic
Don't Panic

Reputation: 41820

"The string will always have "Tmps" followed by something else."

You don't need a regular expression, in that case.

$result = substr($fieldName, 4);

If the first four characters are always the same, just take the portion of the string after that.

Upvotes: 3

Alex Shesterov
Alex Shesterov

Reputation: 27565

$matches = []; // Initialize the matches array first
if (preg_match('/^Tmps(.+)/', $fieldName, $matches)) {
    // if the regex matched the input string, echo the first captured group
    echo($matches[1]);
}

Note that this task could easily be accomplished without regex at all (with better performance): See startsWith() and endsWith() functions in PHP.

Upvotes: 3

The Coprolal
The Coprolal

Reputation: 996

Your regex is flawed. Use this:

preg_match('/^Tmps(.+)$/', $fieldName, $matches);
echo($matches[1]);

Upvotes: 4

Related Questions