Redbox
Redbox

Reputation: 1477

PHP: extract some part of a string variable

i have a variable look like this:

$var1 = "33081PA-5112";

some time it become:

$var1 = "33083";
$var1 = "33081PA-1132";
$var1 = "31183";
$var1 = "13081PA-2132";

how do i determine when it has the PA-, so when it does i want to get the number value after the PA- into other variable.

Thanks

Upvotes: 0

Views: 1022

Answers (6)

j08691
j08691

Reputation: 207901

Use strpos():

if(strpos($var,'PA-') !== false) // code to run if the string has a PA-

Upvotes: 1

Aust
Aust

Reputation: 11602

This will give you what you want.

$var1 = "33081PA-1132";
preg_match('/^([0-9]*)PA-/',$var1,$match);
$var1_cut = $match[1];
preg_match('/PA-([0-9]*)/',$var1,$match);
$var2 = $match[1];

//Outputs
print_r($var1);     //33081PA-1132
print_r($var1_cut); //33081
print_r($var2);     //1132

Upvotes: 1

Jonathan Eckman
Jonathan Eckman

Reputation: 2077

if(trim(str_replace(range(0,9),'', $var1)) == 'PA-') { 
  //do stuff
}

Upvotes: 0

Night2
Night2

Reputation: 1153

<?php

$var1 = "33083";
$var1 = "33081PA-1132";

if(strstr($var1, 'PA') !== false){ // If it has the PA
    $parts = explode('PA-', $var1); // Split by dash

    echo $parts[0]; // Left part
    echo '<br />';
    echo $parts[1]; // Right part
}else{
    echo $var1; // It has not PA
}

?>

Upvotes: 0

Josh
Josh

Reputation: 12566

Here you go:

<?php
    $var1 = "13081PA-2132";
    $pos = strpos( $var1, 'PA-');
    echo $pos . "\n";

    if( $pos > -1 )
    {
        $newVal = substr($var1, $pos+3 );

        echo $newVal;
    }
?>

Output:

5
2132

Upvotes: 1

NedStarkOfWinterfell
NedStarkOfWinterfell

Reputation: 5153

You can do a regex match:

preg_match("{PA-(\d+)}",$var,$array);
echo $array[1][0];

Upvotes: 0

Related Questions