1

The Product name consists of a string - number like:

Chains-23x10 5R 12

I want to display the substring before - in one line and the substring after - in next line. I tried it with the code:

<?php $str = substr($str, ($pos = strpos($str, '-')) === false ? 0 : $pos + 1); ?>
<?php echo $str; ?> 

But only the string after - is getting displayed.

Someone help please.

3 Answers 3

4

Use below code (Tested & Working):

$str = "Chains-23x10 5R 12"; // Pass Product name here
$strArr = explode("-", $str);
//print_r($strArr);
if(count($strArr) == 2){
    echo $strArr[0];
    echo "<br>";
    echo $strArr[1];
}else{
    echo $str;
}
0
2

Try to use the default php explode feature:

$str = 'Chains-23x10 5R 12';
$strParts = explode('-', $str);
print_r($strParts);

echo '<br/>';

echo 'Part 1: ' . (isset($strParts[0]) ? $strParts[0] : ' empty ');
echo '<br/>';
echo 'Part 2: ' . (isset($strParts[1]) ? $strParts[1] : ' empty ');
echo '<br/>';
echo 'Part 3: ' . (isset($strParts[2]) ? $strParts[2] : ' empty ');

The result should be the following:

enter image description here

1

You can hold product name in a variable and then use explode php function to explode name with -.

For example:

$productName = 'Chains-23x10 5R 12';
$arr = explode('-',$productName);

echo $arr[0];

echo $arr[1];

If there can be more than 1 -, then you can loop through $arr array.

2
  • See my updated question
    – Ramya
    Jul 26, 2016 at 10:01
  • Please check my updated answer. Jul 26, 2016 at 10:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.