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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

preg_replace with backreference AND curly braces 1

Status
Not open for further replies.

OsakaWebbie

Programmer
Feb 11, 2003
628
JP
Trying to use PHP to construct TeX code, and TeX loves curly braces. But in PHP, curly braces are interpreted as part of parsing variables. I have strings like "Dm7 G" (yes, they are guitar chords), and want them to become like "Dm\Sup{7} G".

If I do this:
PHP:
preg_replace("/([0-9]+)/","\\Sup{$1}",$chord)
I get a syntax error.

But if I do this:
PHP:
preg_replace("/([0-9]+)/","\\Sup\{$1\}",$chord)
the backslashes actually end up in the resulting string, which is not desired.

Suggestions?
 
Hi

OsakaWebbie said:
But in PHP, curly braces are interpreted as part of parsing variables.
Correct. So you have to stop the variable parsing :
PHP:
[COLOR=darkgoldenrod]preg_replace[/color][teal]([/teal][green][i]"/([0-9]+)/"[/i][/green][teal],[/teal][green][i]"\\Sup{[highlight]\[/highlight]$1}"[/i][/green][teal],[/teal][navy]$chord[/navy][teal]);[/teal]

May be caused by my affinity for shell scripting, but I generally prefer to use the most restrictive quoting possible in each case. In this case I would use single quotes ( ' ) :
PHP:
[COLOR=darkgoldenrod]preg_replace[/color][teal]([/teal][green][i]'/([0-9]+)/'[/i][/green][teal],[/teal][green][i][highlight #fcc]'[/highlight]\\Sup{$1}[highlight #fcc]'[/highlight][/i][/green][teal],[/teal][navy]$chord[/navy][teal]);[/teal]

Feherke.
[link feherke.github.com/][/url]
 
Thanks! I must be losing my mind - I thought I tried that second version (among various things I tried in desperation) and got an error. Anyway, naturally you know what you're doing, and both solutions work.

feherke said:
So you have to stop the variable parsing...
I'm a little confused - when I stop the parsing (either by escaping the $ or using single quotes), why don't I end up with a literal "Dm\Sup{$1} G"?
 
Hi

OsakaWebbie said:
when I stop the parsing [gray](...)[/gray] why don't I end up with a literal "Dm\Sup{$1} G"?
In this case $1 is not a variable, it is a placeholder. The [tt]preg_replace()[/tt] function replaces such placeholders after her finds a substring matching the regular expression and extracted the captured groups.

Variable parsing had to be stopped to avoid the PHP interpreter trying to interpret $1 as variable before the [tt]preg_replace()[/tt] function receives its string parameters.

Feherke.
[link feherke.github.com/][/url]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top