Question:
I have the following String:
$link = '13542345/essa_e_minhastring';
How do I get only the value up to the slash "/" and ignore the rest?
I would like to assign this value to a variable.
I'm using the following code, but it just breaks the string…and doesn't separate it into a variable like I need:
$cod = str_replace("/","<br>",$link);
echo $cod;
The result is:
13542345
this_and_mystring
I need it to be just:
13542345
Answer:
You can split the string by /
using explode()
and then just use the first part like this:
$partes = explode("/", $link);
echo $partes[0]; // dá 13542345
Example: https://ideone.com/oAnXfR
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: https://ideone.com/4GGZbY
I did a test between explode
, preg_match
, strtok
and substr
. The test certainly fails 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