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

Asked

Viewed 60 times

2

I am trying, unsuccessfully to cut a string from a character contained in it, first I need to find the _ in the string, after finding it I need to cut the same one to it and after it to the ponto, if you do not find the character I need to cut the string to the point. Follow 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 _ need to cut the string to the point playing in a variable, so:

$Id = 3803

If the _ I need to cut the string to it and after it to the point by playing each one in a variable.

Would something like this:

$Id = 3803;
$Seq = 452;

2 answers

3


You can split/explode by this character, and 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: https://ideone.com/VClG5Y

Alternative, more semantic (correcting a problem that Everson raised) would only work with the 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: https://ideone.com/smqebV

  • Hello @Sérgio, good morning, I appreciate the help, I’ll change the question, I don’t need the . jpg of the string, only the values.

  • @adventistapr this was clear in the question. I had not noticed it well and now I have corrected.

  • 1

    I appreciate the great help.

  • 1

    The $seq = substr($seq, 0, strpos($seq, '.')); can be done directly on $ID since it is a party that does not matter. And also that the restriction of the question applies if you do not find the character need to crop the string to the point, then there won’t be $partes[1] this will generate a Warning in PHP

  • @Everson well seen! I corrected, thank you!

  • @Magichat you’re right. I fixed!

  • @Magichat is working. It must be an Ideone cache problem. I had tested by taking out the _ and he kept this stdout... I clicked on Save again and cleaned.

Show 2 more comments

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 on Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.