Return last characters from a string in PHP

-1

I am trying to incorporate some of Infomoney's financial information into my application, and in the Investment Fund part it gives the ranking of the top portfolios. But it returns the following string :

  

1st MCR-MAIN INVESTMENT FUND IN SHARES +97.01%

I needed to explode this string in 3 parts:

1st ranking of the portfolio 2nd name of the wallet 3rd profitability index

I'm using this script:

if(!$fp=fopen("https://www.infomoney.com.br/mercados/fundos" , "r" )) 
{
    echo "Erro ao abrir a página de indices" ;
    exit;
}
$conteudo = '';
while(!feof($fp)) 
{ 
    $conteudo .= fgets($fp,1024);
}
fclose($fp);

$valorCompraHTML    = explode('class="numbers">', $conteudo); 
$ibovespa = trim(strip_tags($valorCompraHTML[$campo]));
$ibovespa = preg_replace(array("/\t/", "/\s{2,}/", "/\n/", "/\r/"), array("", " ", " ", " "), $ibovespa);
$ibovespa = explode(' ', $ibovespa);
$cart = trim($ibovespa[$explo]);

I have already found several articles about returning the first few characters of a string. But how to return the last 8? I even found something on the internet, but I could not interpret it. The code looks like this:

set @p = (SELECT LOCATE('+', '$xcart'));
SELECT SUBSTRING( 'xcart' , @p - 1 , @p + 5 );
    
asked by anonymous 02.10.2017 / 17:56

2 answers

0

I made this function to test and it is returning the last 8 elements of a string:

$get = $_GET['id'];

if(2==2)
{
    echo ultimos8($get);
}

function ultimos8($value)
{
    $var = $value;
    $tamanhoVar = mb_strlen($var);
    var_dump($tamanhoVar);
    $ultimos8 = substr($var, -8);
    $tamanhoVar8 = mb_strlen($ultimos8);
    var_dump($tamanhoVar8);
    var_dump($ultimos8);
}

The function that takes the last 8 values is substr , I left even with var_dumps for you to test if you want.

Just what's needed to work:

function ultimos8($value)
{
    $var = $value;
    $ultimos8 = substr($var, -8);

    return $ultimos8;
}

What you need:

<?php
$value = '1º MCR-PRINCIPAL FUNDO DE INVESTIMENTO EM AÇÕES +97,01%';

if(2==2)
{
    echo ultimos8($value);
}

function ultimos8($value)
{
    $var = $value;
    $ultimos8 = substr($var, -8);

    return $ultimos8;
}
?>
    
02.10.2017 / 18:33
0

Look, you can use a regular expression to get the information much simpler, that would be it here:

<?php
  $string = "1º MCR-PRINCIPAL FUNDO DE INVESTIMENTO EM AÇÕES +97,01%";
  preg_match("#(\d[^-]+)-(.*)([+-].*)#", $string, $matches);
  list($textMatch, $ranking, $nome, $indice) = $matches;

   print "1ª ranking da carteira: $ranking, 2ª nome da carteira: $nome, 3ª índice de rentabilidade: $indice";

Embrace, and be happy, expressão regular (regex) will save your life whenever you allow rsrsrs.

But answering your question exactly, just use - , which would look like this:

<?php
  $string = "1º MCR-PRINCIPAL FUNDO DE INVESTIMENTO EM AÇÕES +97,01%";
  echo substr($string, -8); //Pegando apenas os últimos 8 caracters
    
02.10.2017 / 19:12