You should use preg_match_all
when there are multiple values, see your documentation here!
To "catch":
This is to ONLY get the data between "/", that way you will be able to get "whatever you have" between the "/". You will also get to use them to replace. Since your posting says you need "$ string" and also "$ removed", that would be the best 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 do one:
foreach($resultado[1] as $texto){
echo $texto;
}
You'll get:
dolor sit amet
adipiscing elit
To remove:
Using the data already obtained with preg_match_all:
This is useful if you need to get the data using preg_match_all
, so it will only replace what you already have!
$string = 'Lorem ipsum /dolor sit amet/, consectetur /adipiscing elit/.';
$resultado = str_replace($resultado[0], "", $string);
echo $resultado;
// Retorna:
Lorem ipsum , consectetur .
Using preg_replace:
This solution does not fully answer the question since the author requires the "$ withdrawn"!
For other cases, when there is only need to replace, without obtaining any data, 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 REGEX:
Regex is the main function of this function, so I should at least explain it minimally.
/ 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)
In this way REGEX performs something like:
Find the "/", get anything until you find the next "/", thus getting everything that is between the "/".