Jump to content
php.lv forumi

Recommended Posts

Posted (edited)

Labdien.

Saskāros ar stringa formatēšanas problēmām..(līkām rokām :) )

 

Ir: multiselect forma kurā stāv: 30ml. 100ml, 500ml, 1pcs, 5pcs, 100pcs: taču jāizvada kaut kas līdzīgs = 30/100/500ml/1/5/100pcs, (šeit selektotas visas vērtības).

 

Ar str_replace varētu no stringa aizvākt visus "ml" un "pcs".

$string = "30ml/100ml/500ml/1pcs/5pcs/100pcs";
$remove = array("ml","pcs");
$new = str_replace($remove, "", $string);

Tikai pašam pēdējam jāpiekabina klāt vai nu "ml" vai "pcs".

$goal = "30/100/500ml/1/5/100pcs";

Ir kādas idejas?

Pateicos.

Edited by Pieduriens
Posted


$string = "30ml/100ml/500ml/1pcs/5pcs/100pcs";

 

$rev_arr = array_reverse(explode("/", $string));

$used = array();

array_walk($rev_arr, function(&$v, $k, &$used) {

$match = null;

preg_match('/([0-9]+)([^0-9]+)/', $v, $match);

$str = isset($match[2]) ? $match[2] : "";

if (in_array($str, $used)) {

$v = isset($match[1]) ? $match[1] : "";

} else {

$used[] = $str;

}

}, $used);

 

$new_string = implode("/", array_reverse($rev_arr));

 

Posted
echo preg_replace('#(\d+)[^/]+/#', '$1/', '30ml/100ml/500ml/1pcs/5pcs/100pcs');

Strādā tikai ja ir izmantots vai nu ml vai pc, kopā ne.

Posted

Droši vien var smukāk, bet ienāca prātā kaut kas šāds:

$string = "30ml/100ml/500ml/1pcs/5pcs/100pcs";
echo preg_replace('/ml/','',preg_replace('/pcs/','',$string,substr_count($string,'pcs')-1),substr_count($string,'ml')-1);
Posted
$s="30ml/100ml/500ml/1pcs/5pcs/100pcs";
echo preg_replace('/([a-z]+)(?=.*\1)/','',$s);

Kā ar šo?

 

Un aiziet: kuram īsāk :)

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...