Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

php character replace 2

Status
Not open for further replies.

jim1202

Programmer
Aug 12, 2005
3
US
I need a little help. I need to substitute a ^ for a - but only in certain instances. This is an example I need a fix for - for the string 'abcd-efgh_zzzz_xxxx-1-99' I only need to replace the - if the hyphen is located next to a number. So in the example the correct result should be 'abcd-efgh_zzzz_xxxx^1^99'

Anyone?
 
jim1202:

547n is right. You'll need a regular expression. Or perhaps more than one.

I can do it with two regular expressions. This script

Code:
<?php
$a = 'abcd-efgh_zzzz_xxxx-1-99';

$a = preg_replace ('/(\d)-/', '$1^', $a);
$a = preg_replace ('/-(\d)/', '^$1', $a);

print $a;
?>

outputs

abcd-efgh_zzzz_xxxx^1^99


Want the best answers? Ask the best questions!

TANSTAAFL!!
 
How about this:

Code:
<?php
$str =<<<END
This is a line of text with abcd-efgh_zzzz_xxxx-1234-956569 in it.
This is a line without the prefix xxxx-1234-956569
This is a line of text with 1234-956569 in it.
This is a line of text with abcd-efgh_zzzz_xxxx-1-99 in it.
END;

echo "<pre>";
echo preg_replace("/(-)([\d]+)(-)([\d]+)/", "^\\2^\\4", $str);
echo "</pre>";

?>

One question, do you need to test for the prefix(abcd-efgh_zzzz_xxxx)
or is this the only occurence of the -1-99?

Thanks,
 
thanks very much. I was having a lot of trouble with the preg_replace.. not sure I understand the statements now.. but they work great. Thanks very much.
 
Lrnmore - I don't have to test for the prefix it could be any prefix but the ending number combo AA_BB-CC_DD-xx-xx (could be any number of digits really) needs to be have the - replaced with ^.. The ending number combo will always be preceded with an alpha character.. your script seems to do the job in one step.
 
Glad it was helpful.
Thanks for the
star.gif
.

You may know about php.net but in case you don't here's a link:

Thanks,
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top