Jump to content

[SOLVED] How to use Substr


ksduded

Recommended Posts

If I understand you correctly you'd probably want to use explode()

 

ex:

 

<?php
$str = 'CATEGORY: ITEM';
echo next(explode(': ', $str)); // ITEM

 

In case you were wondering: next() is only ultized in my example to grab the second element (index of 1) of the array returned by explode(). Because the default array pointer is 0, so using next() increments that to 1 then returns that element. So it would be no different than doing:

<?php
$str = 'CATEGORY: ITEM';
$arr = explode(': ', $str);
echo $arr[1];

$str = 'CATEGORY: ITEM';

echo next(explode(': ', $str)); // ITEM[/code]

 

Thanks, this worked for me to an extent. However, I want to first check whether the string has CATEGORY: in it before exploding it.... if it does not, then it can move ahead....

 

This is what I am doing

 

 

$str = $title;
$title = next(explode(': ', $str));

 

$title has the string... it can be either ITEM or CATEGORY: ITEM (and it keeps on changing according to the different web page), so ideally i would first check for CATEGORY: inside the title, and if found then only do the explode function.... how do I go about that.

You can use:

 

echo (strpos($str, 'CATEGORY: ') !== false) ? next(explode(': ', $str)) : $str;

Basically what it does is check to see if 'CATEGORY: ' is found inside $str using strpos(). If it does then it explodes and gets ITEM out of it, like in my previous example. If not it just echoes $str

You can use:

 

echo (strpos($str, 'CATEGORY: ') !== false) ? next(explode(': ', $str)) : $str;

Basically what it does is check to see if 'CATEGORY: ' is found inside $str using strpos(). If it does then it explodes and gets ITEM out of it, like in my previous example. If not it just echoes $str

 

Ok, I am being a complete noob here, but I don't want the echo out the result. Just store it in the $str variable.

 

Otherwise it is working out perfectly. Thanks

Here are three more variations on the theme. They all take the variable $str and chomp off the "CATEGORY: " prefix if there is one. The first two require the prefix to be at the start of the string.

 

$str = "CATEGORY: ITEM";

// If prefix exists for string, remove it.
$prefix = "CATEGORY: ";
if (strpos($str, $prefix) === 0) {
    $out = substr($str, strlen($prefix));
}

// Same as above
$out = preg_replace("/^CATEGORY: /", "", $str);

// (Almost) same as above
$out = str_replace("CATEGORY: ", "", $str);

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.