John Magnolia
John Magnolia

Reputation: 16793

php test if string ends with _text + number

I have a couple of issues with this if statement which checks if a string ends with "address".

E.g this matches user_address, user_address1, user_address99, etc. Which is correct.

The problem is that it also matches user_address_location which is not correct.

I only want this to match if:

  1. Is ends with _address
  2. Also if it has a number on the end e.g _address2
/* Only establish an address field as ADDRESS if follows "user_address1" format */
if((stristr($column,"address") !== false)) {
    $parts = explode("_", $column);
    if (!empty($parts)) {
        // address code
    }
}

Upvotes: 2

Views: 200

Answers (5)

John Magnolia
John Magnolia

Reputation: 16793

I wanted to find a way to do it without regular expressions, sorry I should of made that clear in the question.

But I think I have found a way, not sure if it can be improved or performance compared to the regular expressions.

/* First establish it could be an address field e.g "user_address1" format */
$column_address = strpos($column, "_address");
if($column_address !== false) {

    // remove everything before "_address"
    $last = substr($column, $column_address);

    // Check if "_address" OR remove "_address" and check if int
    if($last == "_address" || intval(substr($last, 8))){

Upvotes: 0

Teena Thomas
Teena Thomas

Reputation: 5239

change if((stristr($column,"address") !== false)) { to if(preg_match("/^user_address[0-9]*/", $column) == 1) {

Upvotes: 0

Prasanth
Prasanth

Reputation: 5258

You can make use of $ of regular expressions here. When using regular expressions $ specifies the end of a string

So, you can search for this regular expression:

$regexp = "^.*_address\d+$";

^ is the start, .* indicates any number of any characters _address is what you want to search for, \d+ says it can have numbers after address, and $ indicates end of string.

You can read more about regular expressions, and preg_match on php.net

Upvotes: 1

Flosculus
Flosculus

Reputation: 6946

Use regular expressions:

if(preg_match('/_address(\d+)?$/', $column))
{

}

if you are doing a lot of string comparing and manipulation this web application will be very useful to you: http://gskinner.com/RegExr/

It allows you to develop regular expressions against content with live feedback on matches and replacements.

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227240

This might be a decent place to use a regex

if(preg_match('/^user_addesss\d*$/', $column) === 1){
}

Upvotes: 4

Related Questions