How to find a caraceter in the string and cut string to it and after it

2

I'm trying, unsuccessfully to make a cut of a string from a character contained in it, first I need to find the _ in the string, after finding it I need to cut it to him and after him to the ponto , if it does not find the character I need to cut the string to the point. Here's what I've tried so far;

Finding the character in the string:

$ID = '3803_452.jpg';
$termo = '_';

$padrao = '/' . $termo . '/';

if (preg_match($padrao, $ID)) {

  echo 'Tag encontrada';

} else {

  echo 'Tag não encontrada';

}

If there is no _ I need to cut the string to the point by playing in a variable, thus:

$Id = 3803

If it was found the _ I need to cut the string to it and after it to the point throwing each one into a variable.

It would look something like this:

$Id = 3803;
$Seq = 452;
    
asked by anonymous 04.10.2017 / 13:41

2 answers

3

You can split / explode by this character, so you have the string separated. Then you use substr to limit the second part to . .

$ID = '3803_452.jpg';
$partes = explode('_', $ID);

$id = $partes[0];
$seq = $partes[1];
$seq = substr($seq, 0, strpos($seq, '.'));
echo $id; // 3803
echo $seq; // 452

Example: link

Another alternative, more semantics (correcting a problem that Everson raised would work only with substr :

$ID = '3803_452.jpg';

$id = substr($ID, 0, strpos($ID, '_'));
$seq = substr($ID, strlen($id) + 1, strpos($ID, '.') - strlen($id) - 1);
if (strlen($id) == 0) {
    $id = $seq;
    $seq = '';
}

echo $id; // 3803
echo '<>';
echo $seq; // 452

Ideone : link

    
04.10.2017 / 13:46
3

You can use this combination of preg_split and pathinfo .

<?php
$str = '3803452.jpg';
$chars = preg_split('/_/', $str, PREG_SPLIT_OFFSET_CAPTURE);
if(count($chars) < 2)
{   $ext = pathinfo($str);
    $chars = $ext['filename'];
    echo $chars;
}else
{   echo $chars[0];
}
?>

See Ideone

    
04.10.2017 / 14:16