Jump to content

str explode between symbols?


EchoFool

Recommended Posts

Hey

 

Im trying to use a str_explode but on the basis that the words are "between" the symbol.... heres what i mean:

 

Say i got:

 

#username1#usrname2#

 

becomes username1 and username2

 

username1#username2# is username2 only.

 

and username1#username2 is nothing.

 

I want to seperate with :

 

print_r(explode('#', $str, 2));

 

But specifically with the picky method involved, how do i edit the explode to do it ?

Link to comment
https://forums.phpfreaks.com/topic/187040-str-explode-between-symbols/
Share on other sites

You must be doing something wrong, cuz i get the right output

<?php
  function delim_explode($delim,$string)
  {
      if(in_array($delim,array('/','\\','[',']','(',')'))) $delim="\\{$delim}";
      $pattern="((?<=$delim).*?(?=$delim))+";
      if(preg_match_all("/{$pattern}/",$string,$matches))
      {
          $matches=$matches[1];
      } else
        $matches=array();
      return $matches;
  }
  function sasa_explode($delim,$string)
  {
      $out = explode($delim, $string);
      array_shift($out);
      array_pop($out);
      return($out);
  }
  
  header('Content-Type: text/plain');
  var_dump(delim_explode('#','#username1#username2#'));
  var_dump(delim_explode('#','username1#usrname2#'));
  var_dump(delim_explode('#','#username#usrname2# wasup guys !'));
  var_dump(delim_explode('#','no delimeter'));
  var_dump(sasa_explode('#','#username1#username2#'));
  var_dump(sasa_explode('#','username1#usrname2#'));
  var_dump(sasa_explode('#','#username#usrname2# wasup guys !'));
  var_dump(sasa_explode('#','no delimeter'));
?>

 

I do like sasa's method, simple :)

Tried that with:

 

$text = '#username#usrname2# wasup guys !';

 

     $out = explode('#', trim($text, '#'));
     $string = $out[0];
    Echo $string;

 

But that doesn't seem to work.

 

You are missing something somewhere. My simple code does indeed work.

 

Full script here:

 


$text = '#username#username2# wasup guys!';
$string = explode ('#', trim($text, '#'));
print_r($string);

 

Output using php -f

[david@penny ~]$ php -f explode.php 
Array
(
    [0] => username
    [1] => username2
    [2] =>  wasup guys!
)

 

 

gizmola, given the text from your last post, EchoFool doesn't want " wasup guys!" to be one of the items since it is not surrounded by # characters.

 

That's what I get for not reading the OP carefully enough.  Thanks Salathe... you are right, I missed that nuance entirely.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.