Return last characters from a string in PHP

Asked

Viewed 3,475 times

-1

I’m trying to incorporate some financial information from Infomoney into my application, and in the Investment Fund part it gives the ranking of the main portfolios. Only it returns the following string:

1º MCR-PRINCIPAL EQUITY INVESTMENT FUND +97,01%

I needed to blow this up string in 3 parts:

1st ranking of the portfolio second name of the wallet 3rd rate of return

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 characters of a string. But how to return the last 8? I even found something on the Internet, but I couldn’t interpret it. The code was like this:

set @p = (SELECT LOCATE('+', '$xcart'));
SELECT SUBSTRING( 'xcart' , @p - 1 , @p + 5 );
  • The sql code is for database interaction. Are you using database interaction for anything? Or is your goal purely php, without sql?

  • I’m not using any query no. It’s an Infomoney feature. I edited the question to display the code I’m using

  • I tried to use the code you gave me and I did so: $ptx = substr($iprima, -8); But it is returning the error :" Warning: substr() expects Parameter 1 to be string, array Given in D: xampp htdocs_responsivel views teste2.php on line 116".

2 answers

0

I made this function to test and is returning me 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 the substr, I even left with the var_dumps for you to test if you want.

Just what it takes to work:

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

    return $ultimos8;
}

What do 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;
}
?>
  • Why did you put that 2 == 2 that I didn’t understand? But anyway, it keeps returning the error message "Warning: substr() expects Parameter 1 to be string, array Given in"

  • I put the 2==2 in the if just to enter the if and be clearer understanding. The error says that the substr function expects a string and an array has been provided, in the example I gave, the $value variable received a string as value and worked, make sure you are not providing an array for the substr function.

  • Thanks for the reply Gabriel, but I don’t know the difference between an array and a string :/

0

Look, you can use a regular expression to get the information in a much simpler way, would this be it:

<?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";

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

But to answer your question exactly, just use the -, what would turn out 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
  • Hello Flávio. I did what you recommended, but is returning error message: "Notice: Array to string Conversion in D: xampp htdocs_responsivel teste2.php on line 277 Notice: Undefined offset: 3 in D: xampp htdocs_responsivel teste2.php on line 279 Notice: Undefined offset: 2 in D: xampp htdocs_responsivel teste2.php on line 279 Notice: Undefined offset: 1 in D: xampp htdocs_responsivel teste2.php on line 279 Notice: Undefined offset: 0 in D: xampp htdocs_responsivel views teste2.php on line 279" Where the line 277 defines the string ($string = $iprima) and the line 279 finds the Matches.

  • It happens because he couldn’t match the phrase 1º MCR[...] is sure that your sentence will always follow this pattern of having, 1 digit, first separation be by '-'; then a sentence; then the index ?

  • No Flavio, this pattern does not exist there on the site. That’s why I wanted to return the last 8 characters. The 1st and 2nd positions represent the ranking (1st, 2nd) and are fixed and the last eight positions represent the profitability, so 8 characters. 1 for space (if profitability is greater than 99.99% and less than 999.99%) 1 for the +, 2 for the first digits, 1 for the comma and 2 for the decimal place and 1 for the signal %

  • Use that expression then: preg_match("#(\d[^\s]+)(.*)([+-].*)#", $string, $matches);, but to return the last 8 digits, is there in the answer.

Browser other questions tagged

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