0

i am trying to remove last array after i made an explode on this strings: Example 1

Adress1
Adress2
String1 : String2 

Example 2

Adress1
Adress2
Adress3
String1 : String2 

My idea was first to check if their is a match " : " in string(adrori) then the last array "String1 : String2" should be removed completely. No matther how much array counts would be counted.

Here is my code:

if (preg_match("/ : /", $adrori)) {
    $arr2 = explode("\n", $adrori);
    $adrori = array_pop($arr2);
    $adrori = implode("\n", $adrori);
}   

thanks

4
  • give an example, its hard to follow. Commented Mar 7, 2016 at 11:25
  • I don't understand the examples. Can you please post the output for var_export($adrori); that corresponds to the examples? Commented Mar 7, 2016 at 11:28
  • Do you know that if the string contains “String1 : String2” in first line and “Adress3” in the last line, “Adress3” will be removed? Commented Mar 7, 2016 at 11:36
  • all addresses ends with String : String. Sometimes are two rows and sometimes more than two. But always appears at the end of String the following: ExampleString : ExampleString. So i am trying to remove always the last row with " : " at the end of string. Commented Mar 7, 2016 at 11:37

4 Answers 4

1

array_pop changes its argument and returns the last element. So you should do it like this.

if (preg_match("/ : /", $adrori)) {
    $arr2 = explode("\n", $adrori);
    array_pop($arr2);
    $adrori = implode("\n", $arr2);
}  
Sign up to request clarification or add additional context in comments.

Comments

1

In your example, after removing last array item you re-implode it.

So, you can obtain desired result also using preg_replace, without exploding/imploding:

$adrori = trim( preg_replace( '/.+ : .+$/', '', $adrori ) );

or:

$adrori = preg_replace( '/\n.+ : .+$/', '', $adrori );

Pattern explanation:

\n  newline
.+  one or more characters
 :  space-colon-space
.+  one or more characters
$   end of string

Comments

0

Try this out:

$a = array('a1','a:2');
$b = array_filter($a,function($value){
if(strpos($value, ':') === false){
  return $value;
 }
});
print_r($b);

Comments

0

the example from @ksimka worked! Thank you so much people!

My mistake was to give variable to aray_pop.

Wrong:

 if (preg_match("/ : /", $adrori)) {
        $arr2 = explode("\n", $adrori);
        $adrori = array_pop($arr2);
        $adrori = implode("\n", $adrori);
    }   

right:

 if (preg_match("/ : /", $adrori)) {
        $arr2 = explode("\n", $adrori);
        array_pop($arr2);
        $adrori = implode("\n", $adrori);
    }   

Thank you

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.