Page 1 of 1

String Problems

Posted: Thu Nov 10, 2005 7:33 pm
by PnHoPob
Hey all!

Although I'm not a noob programmer, I'm a noob PHPer :( </ego boost>

Hmm.. how can I explain this? Okay, so I'm trying to this this convertion program that would take a string like this:
HDKRFG:DJFGKJN &GFKDJN& : DSFLKJNDSF&DJNDF:GSG
and convert it with something else.

Now, lets say I'm trying to convert all "DJ"s into "HG"s. that would be:
HDKRFG:DJFGKJN &GFKDJN& : DSFLKJNDSF&DJNDF:GSG

However, I need to ignore everything between two &s and an & and a : . So, this is what would have to be ignored:
HDKRFG:DJFGKJN &GFKDJN& : DSFLKJNDSF&DJNDF:GSG

Everything in olive is ignored, thus only the "DJ" in green has to be converted.


How in the world am I gonna do that? I've been trying to work with str_replace, but have gotten nowhere :(

</ego degration>

Also: is there a function that finds and/or deletes the first few characters in a string?

Posted: Fri Nov 11, 2005 12:27 am
by n00b Saibot
you're better off using preg_* functions for that...

Posted: Fri Nov 11, 2005 12:34 am
by s.dot
Regexes would be your friend for that problem.

As for deleting the first few characters.... substr could work there.

Code: Select all

$newstring = substr($oldstring,3,100);
3 = the character you wish to start at (removing the first 2 characters) and reading till the 100th character.

Posted: Sat Nov 12, 2005 4:48 pm
by PnHoPob
Cool, preg_s and regexes are working well :)

Here's another problem:
I want every [0-9]*[A-Z] to become [0-9][A-Z]. So something like 7*B can become just 7B.

Here's what I've been trying:

Code: Select all

$search = array ('@[0-9]*[A-Z]@');
    $replace = array ('@[0-9][A-Z]@');
    $text = preg_replace($search, $replace, $string);
But of course my output is:

Code: Select all

@[0-9][A-Z]@

What could I do that actually works :P

Posted: Sun Nov 13, 2005 12:48 pm
by twigletmac
Maybe this (main thing is probably escaping the * as that means something special to the regex):

Code: Select all

$search = array ('@([0-9])\*([A-Z])@');
$replace = array ('\1\2');
$text = preg_replace($search, $replace, $string);
Mac

Posted: Wed Nov 16, 2005 1:38 pm
by PnHoPob
So \1 and \2 output [0-9] and [A-Z]? Niice, exactly what I needed, then :)
Thanks so much! I've been asking around like 4 forums and IRC chats and no one could figure it out!

Posted: Fri Nov 18, 2005 7:50 pm
by PnHoPob
Urgh, here's another problem:

How can I count have many times something was preg_replaced?
Like,

Code: Select all

<?php
	$text = "There are lots of ees"
	$match = array('@e@');
    	$replace = array('E');
    	echo preg_replace($match, $replace, $text);
?>
That should echo "ThErE arE lots of EEs".
How can I make it echo 5, since "e" was replaces 5 times by "E"?