replaceText / str_replace [Find and replace text]

-- find     : Text to be found
-- replace  : Text to replace with
-- someText : Text to be searched
on replaceText(find, replace, someText)
	set prevTIDs to text item delimiters of AppleScript
	set text item delimiters of AppleScript to find
	set someText to text items of someText
	set text item delimiters of AppleScript to replace
	set someText to "" & someText
	set text item delimiters of AppleScript to prevTIDs
	return someText
end replaceText

Similar to the PHP function.

-- find    : Text (or list of text) to be found
-- replace : Text (or list of text) to replace with
-- subject : Text (or list of text) to be searched
on str_replace(find, replace, subject)
	set prevTIDs to text item delimiters of AppleScript
	set returnList to true
	
	-- This wouldn't make sense (you could have it raise an error instead)
	if class of find is not list and class of replace is list then return subject
	
	if class of find is not list then set find to {find}
	if class of subject is not list then ¬
		set {subject, returnList} to {{subject}, false}
	
	set findCount to count find
	set usingReplaceList to class of replace is list
	
	try
		repeat with i from 1 to (count subject)
			set thisSubject to item i of subject
			
			repeat with n from 1 to findCount
				set text item delimiters of AppleScript to item n of find
				set thisSubject to text items of thisSubject
				
				if usingReplaceList then
					try
						item n of replace
					on error
						"" -- `replace` ran out of items
					end try
				else
					replace
				end if
				
				set text item delimiters of AppleScript to result
				set thisSubject to "" & thisSubject
			end repeat
			
			set item i of subject to thisSubject
		end repeat
	end try
	
	set text item delimiters of AppleScript to prevTIDs
	if not returnList then return beginning of subject
	return subject
end str_replace

I can’t get this script to work
can you post how you use it?

Hi, Edmund.

It seems that the first parameter should be some text you want to replace, the second should be the text with which you want to replace it, and the third should be the larger text (or texts) in which the first parameter occurs:

str_replace("danced", "[beep]", "I could have danced all night.")
--> "I could have [beep] all night."

str_replace("danced", "[beep]", {"I could have danced all night.", "I could have danced danced danced all night."})
--> {"I could have [beep] all night.", "I could have [beep] [beep] [beep] all night."}

One thing to bear in mind with this handler is that text item delimiters are always case sensitive when dealing with plain text, but with Unicode text, they observe the current setting of the case attribute, which ignores case by default.

-- Plain text. Case sensitive: "danced" is not "Danced".
str_replace("danced", "[beep]", "I Could Have Danced All Night.")
--> "I Could Have Danced All Night."

-- Unicode text. Case insensitive by default: "danced" = "Danced".
str_replace("danced", "[beep]", "I Could Have Danced All Night." as Unicode text)
--> "I Could Have [beep] All Night."

-- Unicode text. Force case sensitivity.
considering case
	str_replace("danced", "[beep]", "I Could Have Danced All Night." as Unicode text)
end considering
--> "I Could Have Danced All Night."

(With thanks to a long-ago instalment of At Last The 1948 Show (I think) for the censored version of I Could Have Danced All Night.) :wink:

ok how come i keep gettings errors when i call a function

functionName()

on functionName()
– do something
end functionName()

no matter what i do i get an error saying it can’t run or find command or something

Hi, Edmund.

The most common reason for not being able to run or find a handler is that the handler call’s in a ‘tell’ block. The thing being ‘told’ then thinks that the call’s supposed to be one of its own commands, whereas it actually belongs to the script. The way round that is to reference the call to the script (‘me’) in one of these ways:

tell application "xyz"
	-- Blah blah blah.

	tell me to functionName()

	-- More blah.
end tell

-- Or:
tell application "xyz"
	-- Blah blah blah.

	my functionName()

	-- More blah.
end tell

Another thing that sometimes happens is that people try to use a variable within the handler with the same name as the handler itself. Setting or changing the value of this variable makes the script lose track of where the handler is.

If neither of these is the cause of your problem, post the details with a script example to the OS X forum and we’ll try to help you sort it out. :slight_smile:

Thanks for the help :slight_smile:

Kyle

Thanks for the input Nigel. :slight_smile:

Can you please give some more details about that? I want to replace case-sensitive unicode text.

Hi, LiMP.

When comparing text, AppleScript normally “ignores” case, so that “LiMP” is regarded as being the same as “LIMP” or “limp”. It’s possible to set the case attribute explicitly to specify this, but you wouldn’t normally bother as it’s the default setting anyway. If you want the comparison to be case-sensitive, then you have to change the case attribute setting temporarily using considering case:

-- Default behaviour:
"LiMP" = "limp" --> true

-- Explicitly specify case insensitivity (not usually necessary):
ignoring case
	"LiMP" = "limp" --> true
end ignoring

-- Specify case sensitivity:
considering case
	"LiMP" = "limp" --> false
end considering

With AppleScript’s older, non-Unicode text classes, the use of text item delimiters wasn’t tied in to the text attribute system, but was entirely case sensitive. If you wanted to replace “LiMP” in your text, you had to use “LiMP” as the delimiter, not “limp” or “LIMP”. But with Unicode text, TIDs do obey the text attribute settings, so if you want case sensitivity, you have to use considering case:

set Utxt to "LiMP limped to the computer." as Unicode text

set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "LiMP"
set TIs to Utxt's text items -- Any case of "LiMP" in Utxt will be replaced.
set AppleScript's text item delimiters to "Fred"
set Utxt2 to TIs as Unicode text
set AppleScript's text item delimiters to astid
Utxt2 --> "Fred Freded to the computer."

-- For case sensitivity with Unicode text:
considering case
	set astid to AppleScript's text item delimiters
	set AppleScript's text item delimiters to "LiMP"
	set TIs to Utxt's text items -- 'considering case' only actually affects this line.
	set AppleScript's text item delimiters to "Fred"
	set Utxt3 to TIs as Unicode text
	set AppleScript's text item delimiters to astid
end considering
Utxt3 --> "Fred limped to the computer."

The considering case and end considering lines turn case sensitivity on and off for the entire script when they’re encountered at run time, so if you put the call to Bruce’s handler between them, the whole of the handler will be executed case sensitively:

set Utxt to "LiMP limped to the computer." as Unicode text

-- Case-insensitive up to here.

considering case
	-- Execute Bruce's handler in case-sensitive mode.
	set Utxt2 to str_replace("LiMP", "Fred", Utxt)
end considering

-- Case-insensitive again.

The above is true for text in the Roman alphabet, but I only presume that it applies to other alphabets too.

Errrrrrr. nope !! What you’re quoting there is from the “Julie Andrews Dirty Songbook” which featured on one of the many episodes of “I’m Sorry I’ll Read That Again”. Oh nostalgia. I was just a kid. sniff :wink:

Oh yes. nearly forgot. very interesting thread - with or without Julie A. :slight_smile:

I’m a little lost. How can I modify this script to do the following.

“This_is_a_test”

Find & replace “_” with " "

I process extremely large amounts of music ID3 tags and I need an easier way to select text and have it automatically remove the specific characters.

For replacing characters you can also use tr command.

do shell script "/bin/echo -n " & quoted form of "This_is_a_test" & " | tr '_' ' '"