How to get content within string up to a "bar /" character

10

I have the following String:

$link = '13542345/essa_e_minhastring';

How do I get only the value up to the "/" bar and ignore the rest?

I'd like to assign this value to a variable.

I'm using the following code, but it just breaks the string ... and does not separate into a variable as I need:

 $cod = str_replace("/","<br>",$link);
 echo $cod;

The result is:

  

13542345
  esse_e_minhastring

I need it to be just:

  

13542345

    
asked by anonymous 28.09.2015 / 23:17

3 answers

13

You can break the string by / using explode() and then use only the first part like this:

$partes = explode("/", $link);
echo $partes[0]; // dá 13542345

Example: link

Another alternative is to use regex like this:

$link = '13542345/essa_e_minhastring';
$pattern = '/[^\/]+/';
preg_match($pattern, $link, $partes, PREG_OFFSET_CAPTURE);
echo $partes[0][0]; // dá 13542345

Example: link

I did a test between explode , preg_match , strtok and substr . The test certainly sins because it is so simple and isolated, and therefore not real. But it's interesting. The result between the 4 methods is:

7.9003810882568E-8 sec / por explode
2.0149707794189E-7 sec / por preg_match // <- mais rápida
4.8128128051758E-8 sec / por strtok
5.2464962005615E-8 sec / por substr
    
28.09.2015 / 23:21
11

The function strstr() , breaks a string by a delimiter and returns the right part by default, passing the third argument to true return is the left part.

$link = '13542345/essa_e_minhastring';
echo strstr($link, '/', true);

Another option is explode() , it transforms the string into an array, just grab the first one element (zero index).

This syntax works from 5.4

$link = '13542345/essa_e_minhastring';
$numero = explode('/', $link)[0];
echo $numero;

for lower versions do:

$link = '13542345/essa_e_minhastring';
$numero = explode('/', $link);
echo $numero[0];

Example - ideone

    
28.09.2015 / 23:21
6

Use the substr () function;

It takes the contents to the bar and continues as a string;

$text = "123456/efineinfe";
$text = substr($text, 0, strpos($text, "/"));
    
16.08.2017 / 18:10