Jump to content
php.lv forumi

aizvietot stringu ar *****


anonīms

Recommended Posts

Man iešāvās prātā, ka viens šejienietis teica: 'Ja Mēs skatāmies kā C++ to implementē - jebkurš strings īstenībā ir masīvs'.

 

Ir funkcija 'str_split()', kas neatbalsta UTF-8 un ir, tur pat - komentāros, uzrakstīta funkcija, kas to atbalsta:

 

 

function str_split_php4_utf8($str) { 
   // place each character of the string into and array 
   $split=1; 
   $array = array(); 
   for ( $i=0; $i < strlen( $str ); ){ 
       $value = ord($str[$i]); 
       if($value > 127){ 
           if($value >= 192 && $value <= 223) 
               $split=2; 
           elseif($value >= 224 && $value <= 239) 
               $split=3; 
           elseif($value >= 240 && $value <= 247) 
               $split=4; 
       }else{ 
           $split=1; 
       } 
           $key = NULL; 
       for ( $j = 0; $j < $split; $j++, $i++ ) { 
           $key .= $str[$i]; 
       } 
       array_push( $array, $key ); 
   } 
   return $array; 
} 

Link to comment
Share on other sites

mhm, codez variants nav utf-8 proof :p

 

function getStarred($s){
   mb_internal_encoding("UTF-8");
   if($l = mb_strlen($s) < 3){
       return $s;
   }
   return mb_substr($s, 1, 1) . str_repeat('*', $l - 2) . mb_substr($s, -1);
}

 

..mans gan ir..

 

EDIT: daGrevis:

mb_str_split($s){
   $a = array();
   for($i=0;$i<=mb_strlen($s)-1;$i++){
       $a[] = mb_substr($s, $i, 1);
   }
   return $a;
}

Edited by briedis
Link to comment
Share on other sites

Atkal uzdevums, kurš uztaisīs īsāko funkciju?

 


function f($s){return str_pad($s[0],$l=strlen($s)-1,'*').$s[$l];}

 

PHP_FUNCTION(magic_replace)
{
char* text;
int text_length;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &text, &text_length) == FAILURE) {
 return;
}
memset(text + 1, '*', text_length -2);
RETURN_STRING(text, 1);
}

 

function f($s){return str_pad($s[0],$l=strlen($s)-1,'*').$s[$l];}
$loops = 100000;
$string = str_pad('', 10000, '0');
$timer = new Timer();
$timer->start();
for($i = 0; $i < $loops; $i++){
f($string);
}
$timer->stop();
echo 'f()' . $timer . "\n";
$timer->start();
for($i = 0; $i < $loops; $i++){
magic_replace($string);
}
$timer->stop();
echo 'magic_replace() ' . $timer . "\n";

 

f()15.173057079315
magic_replace() 0.45169615745544

 

:P

Link to comment
Share on other sites

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...