You must use the preg_match_all
when there are multiple values, see your documentation here!
To "catch":
This is to ONLY get the data between "/", so you can get "what you have" between "/". You will also be able to use them to replace. Since your post says you need "$string" and also "$withdrawn", this would be a better solution.
// Sua string:
$string = 'Lorem ipsum /dolor sit amet/, consectetur /adipiscing elit/';
// Regex (leia o final para entender!):
$regrex = '/\/(.*?)\//';
// Usa o REGEX:
preg_match_all($regrex, $string, $resultado);
You will get exactly, in the $result variable:
array(2) {
[0]=>
array(2) {
[0]=>
string(16) "/dolor sit amet/"
[1]=>
string(17) "/adipiscing elit/"
}
[1]=>
array(2) {
[0]=>
string(14) "dolor sit amet"
[1]=>
string(15) "adipiscing elit"
}
}
So you can make a:
foreach($resultado[1] as $texto){
echo $texto;
}
Will get:
dolor sit amet
adipiscing elit
To remove:
Using the data already obtained with the preg_match_all:
This is useful if you need to get the data using preg_match_all
, this way will only replace what already has!
$string = 'Lorem ipsum /dolor sit amet/, consectetur /adipiscing elit/.';
$resultado = str_replace($resultado[0], "", $string);
echo $resultado;
// Retorna:
Lorem ipsum , consectetur .
Using the preg_replace:
This solution does not fully answer the question, as the author requires the "$withdrawal"!
For other cases, when there is only need to replace, without obtaining any data, you can use such a method.
$string = 'Lorem ipsum /dolor sit amet/, consectetur /adipiscing elit/.';
$resultado = preg_replace('/\/(.*?)\//', "" , $string);
echo $resultado;
// retorna:
Lorem ipsum , consectetur .
About the REGEX:
The Regex is the main of this function, so I must at least explain.
/ Inicio do Regex!
\/ Escapa o "/" ("encontre a "/")
(.*?) Obtenha qualquer caractere
\/ Escapa o "/" ("encontre a "/")
/ Fim do Regex (como estamos com o preg_match_all seria o mesmo de /g)
So REGEX executes something like:
Find the "/", get anything until you find the next "/", so you get everything that’s between the "/".
http://stackoverflow.com/questions/5696412/get-substring-between-two-strings-php This is what you want!
– caiocafardo
There’s only one problem there:
/, consectetur /
is also between bars.– Ivan Ferrer
The ideal in this case is always you define where it starts and where it ends.
– Ivan Ferrer
Exactly that’s the problem, but the string comes to me like this.. It would be possible for him to identify the // and change to <> for all for example?
– Fleuquer Lima
vc would have to have a string like this: Lorem ipsum [dolor sit Amet], consectetur [adipiscing Elit].
– Ivan Ferrer