TheJason
TheJason

Reputation: 504

ColdFusion RegEx Replacing Tags within a string

I'm trying to ReReplace the actual beginning/ending tags within a string.  
For example, I want to replace  

<p class="style4">My Title Is This<p>

with
<h2>My Title Is This</h2>


I wrote the code below, which seems to find the tags properly within my string, but it's replacing it with <h2>(.+?)</h2>

<cfset this.text2 = ReReplaceNoCase(getThis.statictext, '<p[^>]+class="style4"[^>]*>(.+?)</p>', '<h2>(.+?)</h2>', "ALL")>


Can anyone tell me what I'm missing here?

Thanks

Upvotes: 0

Views: 2884

Answers (2)

David Faber
David Faber

Reputation: 12485

In place of this: '<h2>(.+?)</h2>' you'll want to use the backreference \1 to refer to the subexpression (.+?):

<cfset this.text2 = ReReplaceNoCase(getThis.statictext, '<p\s[^>]+class="style4"[^>]*>(.+?)</p>', '<h2>\1</h2>', "ALL")>

Hope this helps.

UPDATE: Edited per Mike Causer's suggestion below.

Upvotes: 2

WilGeno
WilGeno

Reputation: 185

This finds all tags and just removes them, you can easily modify this to do a replace.

<!--- 
# STRIPTAGS
# Strip all html tags from a string 
# Receive string and return string with any and all tags striped out
--->
<cffunction name="stripTags" access="public" output="false" returntype="string" hint="Remove all HTML tags from string">
    <cfargument name="string" type="any" required="true"  hint="String to clean"/>
    <cfset var pattern = "<[^>]*>">
    <cfreturn REReplaceNoCase(arguments.string, pattern, "" , "ALL")>
</cffunction>

Upvotes: 0

Related Questions