Jump to content

The PHP Challenge


The Little Guy

Recommended Posts

  • Replies 88
  • Created
  • Last Reply
[code]
<?php
function my_trim($str,$charlist)
{
$pattern[0] = "/^\s+/";
$pattern[1] = "/\s+\$/";
$str = preg_replace($pattern,"",$str);
                if(!empty($charlist) || $charlist != '')
              {
                  if(is_array($charlist))
                  {
                    foreach($charlist as $char)
                      $str = ereg_replace($char,"",$str);
                  }
                  else
                    $str = ereg_replace($char,"",$str);
}
                  return $str;
}
$trim = "    LOT OF SPACES HERE    ";
echo my_trim($trim,'');
?>
[/code]

I used patterns this time.
I forgot to mention all you need to remove the spaces (including white-spaces, newlines, tabs etc as said in  the manual) from the [b]beginning and end[/b] of the string. The function doesn't need to include the optional charlist parameter (although if you want to add it, you are welcome :)).

Orio.
This code returns the number of characters that are the same in both strings
[code]
function check_text($string1,$string2)
{
$count=0;
$same=0;
while($string1{$count}!="" && $string2{$count}!="")
{
if(strcmp($string{$count},$string2{$count}))
{
$same++;
}
$count++;
}
return $same;
}
[/code]
[quote author=neylitalo link=topic=119299.msg519609#msg519609 date=1170400107]
fert: I've never seen this, can you explain it?

[code]$string1{$count}[/code]
[/quote]

It takes the [tt]$count[/tt]th character in string.

Example: [code]<?php
$string = "abcdef";

echo $string{0};  // echoes the 0th character in $string (a)
echo $string{2};  // echoes the 2nd character in $string (c)
echo $string{2+1}; // echoes the 3rd character in $string (d)

echo "\n";

for($i=strlen($string)-1; $i >= 0; $i--)
{
echo $string{$i}; // using a variable instead of an integer
}
?>[/code]
The above example outputs: [code]acd
fedcba[/code]

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.