pas_oui
pas_oui

Reputation: 87

PHP delete everything after comma (including comma)

I just can't get my head around the syntax for this. I have an array $foo and I call it within a function: wp_list_pages($foo); (this is a wordpress site).

I found this code online but can't get it to work... I've tried both of these ways and it doesn't seem to do anything. Can anyone help?

 <?php $mystring = $foo;
list ($before,$after) = split (',', $mystring);
echo $before; 
?>
<?php wp_list_pages( $foo ); ?> 

or this:

<?php $has_comma = (stristr($foo, ",")>-1) ? 1 : 0;
if ($has_comma) {
list ($before,$after) = split (',', $foo);
$foo = $before;
} ?>

<?php wp_list_pages( $foo ); ?> 

Upvotes: 0

Views: 2491

Answers (4)

lupatus
lupatus

Reputation: 4248

if (false !== ($pos = strpos($foo, ','))) {
    $foo = substr($foo, 0, $pos);
}

or if you're sure that there is always coma, it can be simplier:

$foo = substr($foo, 0, strpos($foo, ','));

Upvotes: 4

CoursesWeb
CoursesWeb

Reputation: 4237

split() is deprecated, try use preg_split(), or str_split(), see in php manual: http://www.php.net/manual/ro/function.split.php

Upvotes: 0

RonaldBarzell
RonaldBarzell

Reputation: 3830

That example is a bit too convoluted. Here's a simpler one:

<?php 
$mystring = "a,b,c,d egg";
$n = strpos($mystring, ',');
echo substr($mystring, 0, $n)
?>

This one just finds the index of the first "," in $mystring and gets the string up until that point.

If you want an array-based example, here is one that uses explode, since split is deprecated:

<?php 
$mystring = "a,b,c,d egg";
$array = explode(',', $mystring);
echo $array[0];
?>

So explode splits $mystring on "," so that each item separated by a "," becomes its own element. Naturally the first item is the 0th index, so that's how you truncate after the commas.

Upvotes: 0

alanmanderson
alanmanderson

Reputation: 8200

assuming $foo has some string in it for example "This is a short, boring sentence", then:

list($before,$after) = split(',',$mystring)
//$before => "This is a short" 
//$after => "boring sentence"
echo $before; //prints "This is a short"

If you are not seeing this behavior you need to make sure $foo has some string in it.

Upvotes: 0

Related Questions