Jump to content

Help with explode()


Guest

Recommended Posts

$tshirt is the name of articles followed by a code "A123456789". The code is random numbers but always begin by "-A"

 

I'm trying to get the name of the article WITHOUT the number code

 

Here's the code i am currently using:

$tshirt = "Name-of-the-tshirt-A123456789";
$categorie = explode("-A", $tshirt);
$categorie = $categorie[0];
echo $categorie;

 

Problem with this code is that it is bugged if the article looks like this :

$tshirt = "tshirt-anime-A123456789";

 

Then the result will be "tshirt" when it's supposed to be "tshirt-anime"

 

How can i add some sort of wildcard to be sure that "-A" is followed by a number ?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/266144-help-with-explode/
Share on other sites

You want the description without the number, right? Assuming all the numbers are always at the end, explode on the hyphen, array_pop the last element off the array, then implode the array with a  hyphen as the glue.

Link to comment
https://forums.phpfreaks.com/topic/266144-help-with-explode/#findComment-1363878
Share on other sites

In this case, I could use regEx,

take a look at suggestions:

 

// match any characters in the string

$tshirt = "Tes-t, ... Testzaz ^5 &&, Name-of-athe-tshirt-A123456759 Test after";

$pattern = '/[A-Za-z-\S]+(?=\-A\d)/';

if(preg_match($pattern, $tshirt, $matches)){
    
  echo '<pre>'.print_r($matches, true).'</pre>';  
  
}

// match any characters in the string

$tshirt = "Test, ... Testzaz ^5 &%, Name-of-*&%athe-Atshirt-A123456789 Test after";

$pattern = '/[.\S]*(?=\-A\d+)/';

if(preg_match($pattern, $tshirt, $matches)){
    
  echo '<pre>'.print_r($matches, true).'</pre>';  
  
}

// match string which contains at least 9 digits in the end
$tshirt = "Test, ... Testzaz ^5 &%, New-Code-Name-of-athe-tshirt-A123456889 Test after";

$pattern = '/[A-Za-z-\S]+(?=\-A\d{9})/';

if(preg_match($pattern, $tshirt, $matches)){
    
  echo '<pre>'.print_r($matches, true).'</pre>';  
  
}

Link to comment
https://forums.phpfreaks.com/topic/266144-help-with-explode/#findComment-1363903
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.