Take part of a string delimited between characters

Asked

Viewed 14,748 times

1

I have a string as in the example below:

$string = 'Lorem ipsum dolor sit amet, consectetur /adipiscing elit/.';

My question is, how can I only get the part of the text that’s between the bars /, and at the same time remove that part of the string leading?

You’d have to be like:

$string = 'Lorem ipsum dolor sit amet, consectetur.';
$retirado = 'adipiscing elit';

I used this text as an example, but I can have this tag with // in more than one part of my string, and would need to take all these parts separately and remove from the string leading;

Example:

$string = 'Lorem ipsum /dolor sit amet/, consectetur /adipiscing elit/.';

Expected exit:

$string = 'Lorem ipsum, consectetur.'
$retirado = 'dolor sit amet adipiscing elit';
  • 1

    http://stackoverflow.com/questions/5696412/get-substring-between-two-strings-php This is what you want!

  • There’s only one problem there: /, consectetur / is also between bars.

  • The ideal in this case is always you define where it starts and where it ends.

  • 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?

  • vc would have to have a string like this: Lorem ipsum [dolor sit Amet], consectetur [adipiscing Elit].

5 answers

3


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 "/".

  • And how do I retrieve the original part of the string? Without the /parts? Can I use it to replace it as well?

  • I edited for this. Just use the str_replace, I think it has even been mentioned here and then use the array. See the documentation at http://php.net/manual/en/function.str-replace.php.

2

In this case you can use one of the functions split of PHP

One of the simplest ways would be using explode() that would look like this:

$string = 'Lorem ipsum dolor sit amet, consectetur /adipiscing elit/.';
$pices = explode("/", $string);
//Array ( [0] => Lorem ipsum dolor sit amet, consectetur [1] => adipiscing elit [2] => . )

In that case the function explode() generates an array with the string.

Also you can use the functions:
preg_split
or
preg_replace

In that case you would use regular expressions

I hope I’ve helped.

update

To present separately you can do so:

foreach ($pices as $key => $value) {
    echo "<p><strong>Pedaço $key: </strong>$value</p>";
}
  • But if I have an affair with more than one part containing /, how will I know using explode which part of the array to pick up?

  • The blast will give you one array. If you want to manipulate you can make a foreach or something like that. After separating the data what would you do with it ? It was not very clear the purpose.

  • I separate the data to present in different fields

  • I edited the question to see if it’s clearer

  • It’s like you said. You can have one, two or ten pieces. With this you have to do it dynamically. I’ll add the presentation code to see if it helps you.

  • split() was depreciated and removed.

Show 1 more comment

1

You can use the preg_replace as shown below:

preg_replace("/\/(.*\//", "", $string);

1

Function split_me($string,$start,$end){

$str2 = substr(substr($string, strips($string, $start)), strlen($start); $b = strips($str2, $end); Return Trim(substr($str2, 0, $b)); }

$string = 'Lorem ipsum dolor sit Amet, consectetur /adipiscing Elit/. '; echo split_me($string,'/','/');

1

Try it like this:

$string = 'Lorem ipsum /dolor sit amet/, consectetur /adipiscing elit/.';

function removeParseContentBar($string)
{
    $arr = str_split($string);
    $i = 0;
    foreach ($arr as $k => $char) {
        if ($char == '/') {
          /* abre a tag na primeira barra e
             fecha o elemento em tag quando 
             achar a segunda barra */
          $arr[$k] = ($i % 2 == 0) ? '<' : '/>';
        } else {
          $arr[$k] = $char;
          $i++;
        }
        $i++;
    } 
    $content = implode('', $arr);
    //remove a tag
    return strip_tags($content); 
}
echo removeParseContentBar($string);

See working here

  • It works to remove when there is only one part marked, but if there is more than one as I put in the question it takes out extra parts...

  • I edited, @Fleuquerlima, now I believe you will do exactly what you need.

  • Your old code using REGEX: /\/(.*?)\// instead of /\/.*\//i, funcia. See here: https://ideone.com/d44tyU

Browser other questions tagged

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