Jump to content
cdeb

Why doesn't StringReplace() work?

Recommended Posts

As for the object, in this case the StringReplace() function does not work for me.

These are my steps:

1) Extract the subject from an EML file.

ss_subject.png.3a6e11e1336dc70848f8ba459229b595.png (the first character is an emoji )

source from EML file: 

$sSubject = "?utf-8?B?8J+TiCA1IG9mIHRoZSBCZXN0IFN0b2NrcyB0byBCdXkgZm9yIERlY2VtYmVy?="

2) in this case I perform a decoding with _QuotedPrintable_DecodeEncodedWord()

output is: 

$sSubject = "?? 5 of the Best Stocks to Buy for December"

 

3) I perform StringReplace():

$sSubject = StringReplace($sSubject, "??", "")

or

$sSubject = StringReplace($sSubject, Chr(63)&Chr(63), "")

 

But the characters ?? they are not replaced.
 

Yet if I make an Asc of every character of the string with a for loop, are the first two characters really? that is 63

For cycle

        Local $aArray = StringSplit($sSubject, "", $STR_NOCOUNT)
        For $i = 0 To UBound($aArray)-1
            ConsoleWrite($aArray[$i] & " - " & Asc($aArray[$i])& @CR)
        Next

Output:        
? - 63
? - 63
  - 32
5 - 53
  - 32
o - 111
f - 102
  - 32
t - 116
h - 104
e - 101
  - 32

Does anyone have an explanation of why it doesn't work?
Thank you all

 

Edited by cdeb

Share this post


Link to post
Share on other sites

I can't use StringTrimLeft because it's not where and where the characters to be replaced will be.

Here is a snipped where StringReplace doesn't work.

there is also a for loop where the character is displayed? is the number 63

 

#include <Array.au3>


$sEML = "Message-ID: <20191203114629.18789103.20749@sailthru.com>"&@CRLF
$sEML &= "Subject: =?utf-8?B?8J+TiCA1IG9mIHRoZSBCZXN0IFN0b2NrcyB0byBCdXkgZm9yIERlY2VtYmVy?="&@CRLF
$sEML &= "MIME-Version: 1.0"&@CRLF

ConsoleWrite(">>> $sEML: "&@CRLF&$sEML&@CRLF)


$sSubject = _QuotedPrintable_DecodeEncodedWord($sEML)
ConsoleWrite(">>> $sSubject (_QuotedPrintable_DecodeEncodedWord): "&@CRLF&$sSubject&@CRLF)

$sSubject = StringReplace($sSubject, "??", "")  ; <---------------------------- ERROR?
ConsoleWrite(">>> $sSubject (StringReplace): "&@CRLF&$sSubject&@CRLF)



Local $aArray = StringSplit($sSubject, "", $STR_NOCOUNT)
For $i = 0 To UBound($aArray)-1
    ConsoleWrite($aArray[$i] & " - " & Asc($aArray[$i])& @CR)
Next



; ###############################################################################################################################
; ###############################################################################################################################
; ### Quoted-printable.au3 ######################################################################################################
; ###############################################################################################################################
; ###############################################################################################################################

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7
#include-once
; #INDEX# =======================================================================================================================
; Title .........: UDF to Decode Word Encoded with Quoted Printable
; AutoIt Version : 3.3.10.2++
; Language ......: English
; Description ...:
; Author(s) .....: Prog@ndy
; Modified ......: mLipok
; ===============================================================================================================================
#cs
    Author original post
    https://autoit.de/index.php/Thread/11350-UTF8-Sting-Convertieren/?postID=87721#post87721

    Quoted-Printable
    http://tools.ietf.org/html/rfc2045#section-6.7
    https://www.ietf.org/rfc/rfc2045.txt
#CE

;~ _QuotedPrintable_Example()

Func _QuotedPrintable_Example()
    Local $sTestString = ''
    #forceref $sTestString
;~ https://autoit.de/index.php/Thread/11350-UTF8-Sting-Convertieren/?postID=87721#post87721
;~ $sTestString = "=?utf-8?b?QmFja3VwIEV4ZWMtTWVsZHVuZzogQXVmdHJhZyBlcmZvbGdyZWljaA==?="
;~ ;    $sTestString = "=?iso-8859-2?Q?3%_na_Otwartym_Koncie_Oszcz=EAdno=B6ciowym?="
;~ ;    $sTestString = "=?iso-8859-2?Q?EndFunc   ;=3D=3D>_MY_EXAMPLE_POP3?="
;~  MsgBox(0, '', _QuotedPrintable_DecodeEncodedWord($sTestString))
;~  MsgBox(0, '', _QuotedPrintable_DecodeEncodedWord("Subject: =?iso-8859-1?Q?=A1Hola,_se=F1or!?="))
EndFunc   ;==>_QuotedPrintable_Example

; #FUNCTION# ====================================================================================================================
; Name ..........: _QuotedPrintable_GetCodepage
; Description ...:
; Syntax ........: _QuotedPrintable_GetCodepage($charset)
; Parameters ....: $charset             - An unknown value.
; Return values .: None
; Author ........: Prog@ndy
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _QuotedPrintable_GetCodepage($charset)
    Local Const $PATH = "HKEY_CLASSES_ROOT\MIME\Database\Charset\"
    Local $alias
    While 1
        $alias = RegRead($PATH & $charset, "AliasForCharset")
        If @error Then ExitLoop
        $charset = $alias
    WEnd
    Local $result = RegRead($PATH & $charset, "InternetEncoding")
    Return SetError(@error, @extended, $result)
EndFunc   ;==>_QuotedPrintable_GetCodepage

; #FUNCTION# ====================================================================================================================
; Name ..........: _QuotedPrintable_MultiByteToWideChar
; Description ...:
; Syntax ........: _QuotedPrintable_MultiByteToWideChar($iCodePage, $dwFlags, $lpMultiByteStr, $cbMultiByte, $lpWideCharStr,
;                  $cchWideChar)
; Parameters ....: $iCodePage            - An unknown value.
;                  $dwFlags             - An unknown value.
;                  $lpMultiByteStr      - An unknown value.
;                  $cbMultiByte         - An unknown value.
;                  $lpWideCharStr       - An unknown value.
;                  $cchWideChar         - An unknown value.
; Return values .: None
; Author ........: Prog@ndy
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _QuotedPrintable_MultiByteToWideChar($iCodePage, $dwFlags, $lpMultiByteStr, $cbMultiByte, $lpWideCharStr, $cchWideChar)
    Local $TypeMBStr = "str"
    If IsPtr($lpMultiByteStr) Then $TypeMBStr = "ptr"
    Local $aResult = DllCall("Kernel32.dll", "int", "MultiByteToWideChar", "UINT", $iCodePage, "DWORD", $dwFlags, _
            $TypeMBStr, $lpMultiByteStr, "int", $cbMultiByte, "ptr", $lpWideCharStr, "int", $cchWideChar)
    If @error Then Return SetError(@error, 0, 0)
    Return $aResult[0]
EndFunc   ;==>_QuotedPrintable_MultiByteToWideChar

; #FUNCTION# ====================================================================================================================
; Name ..........: _QuotedPrintable_TranslateString
; Description ...:
; Syntax ........: _QuotedPrintable_TranslateString($sStringToTranslate, $iCodePage)
; Parameters ....: $sStringToTranslate              - An unknown value.
;                  $iCodePage            - An unknown value.
; Return values .: None
; Author ........: Prog@ndy
; Modified ......: mLipok
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _QuotedPrintable_TranslateString($sStringToTranslate, $iCodePage)
    SetError(0)
    If Not (IsInt($iCodePage) And $iCodePage > 0) Then $iCodePage = _QuotedPrintable_GetCodepage($iCodePage)
    If @error Or $iCodePage = 0 Then Return SetError(1, 0, "")

    Local $iLength = _QuotedPrintable_MultiByteToWideChar($iCodePage, 0, $sStringToTranslate, StringLen($sStringToTranslate), 0, 0)
    Local $Buffer = DllStructCreate("wchar[" & $iLength + 1 & "]")
    If Not _QuotedPrintable_MultiByteToWideChar($iCodePage, 0, $sStringToTranslate, StringLen($sStringToTranslate), DllStructGetPtr($Buffer), $iLength) Then
        Return SetError(2, 0, "")

    EndIf

    Return DllStructGetData($Buffer, 1)

EndFunc   ;==>_QuotedPrintable_TranslateString

; #FUNCTION# ====================================================================================================================
; Name ..........: _QuotedPrintable_Base64Decode
; Description ...:
; Syntax ........: _QuotedPrintable_Base64Decode($s)
; Parameters ....: $s                   - A string value.
; Return values .: None
; Author ........: Eddy
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _QuotedPrintable_Base64Decode($s)
    Local $key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', _
            $t = '', $p = -8, $a = 0, $c, $d, $len = StringLen($s)
    For $i = 1 To $len
        $c = StringInStr($key, StringMid($s, $i, 1), 1) - 1
        If $c < 0 Then ContinueLoop
        $a = BitOR(BitShift($a, -6), BitAND($c, 63))
        $p = $p + 6
        If $p >= 0 Then
            $d = BitAND(BitShift($a, $p), 255)
            If $c <> 64 Then $t = $t & Chr($d)
            $a = BitAND($a, 63)
            $p = $p - 8
        EndIf
    Next
    Return $t
EndFunc   ;==>_QuotedPrintable_Base64Decode

; #FUNCTION# ====================================================================================================================
; Name ..........: _QuotedPrintable_Decode
; Description ...:
; Syntax ........: _QuotedPrintable_Decode($s[, $IsQ = False])
; Parameters ....: $s                   - A string value.
;                  $IsQ                 - [optional] An unknown value. Default is False.
; Return values .: None
; Author ........: Prog@ndy
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _QuotedPrintable_Decode($s, $IsQ = False)
    If $IsQ Then $s = StringReplace($s, "_", " ")
    $s = StringSplit($s, "=")
    Local $result = $s[1]
    For $i = 2 To $s[0]
        $result &= Chr(Dec(StringLeft($s[$i], 2))) & StringTrimLeft($s[$i], 2)
    Next
    Return $result
EndFunc   ;==>_QuotedPrintable_Decode

; #FUNCTION# ====================================================================================================================
; Name ..........: _QuotedPrintable_DecodeEncodedWord
; Description ...:
; Syntax ........: _QuotedPrintable_DecodeEncodedWord($sStringToDecode)
; Parameters ....: $sStringToDecode           - A dll struct value.
; Return values .: None
; Author ........: Prog@ndy
; Modified ......: mLipok
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _QuotedPrintable_DecodeEncodedWord($sStringToDecode)
    Local $aEncodedChunks = StringRegExp($sStringToDecode, "=\?(.+?)\?(.)\?(.*?)\?=", 4)
    ;_ArrayDisplay($aEncodedChunks, "aEncodedChunks")
    If Not @error Then
        Local $aParts
        For $iChunk = 0 To UBound($aEncodedChunks) - 1
            $aParts = $aEncodedChunks[$iChunk]
            Switch $aParts[2]
                Case "B", "b"
                    $aParts[3] = _QuotedPrintable_Base64Decode($aParts[3])
                Case "Q", "q"
                    $aParts[3] = _QuotedPrintable_Decode($aParts[3], True)
            EndSwitch
            $aParts[3] = _QuotedPrintable_TranslateString($aParts[3], $aParts[1])
            $sStringToDecode = StringReplace($sStringToDecode, $aParts[0], $aParts[3])
        Next
    EndIf
    Return $sStringToDecode
EndFunc   ;==>_QuotedPrintable_DecodeEncodedWord

;~ Under construction
;~ Func _QuotedPrintable_DecodeEncodedText($sStringToDecode)
;~  StringSplit(
;~ EndFunc

 

Share this post


Link to post
Share on other sites

Looks like you're dealing with unicode characters. This revised code works for me --

#include <Array.au3>


Global $sEML = "Message-ID: <20191203114629.18789103.20749@sailthru.com>"&@CRLF
$sEML &= "Subject: =?utf-8?B?8J+TiCA1IG9mIHRoZSBCZXN0IFN0b2NrcyB0byBCdXkgZm9yIERlY2VtYmVy?="&@CRLF
$sEML &= "MIME-Version: 1.0"&@CRLF

ConsoleWrite(">>> $sEML: "&@CRLF&$sEML&@CRLF)


Global $sSubject = _QuotedPrintable_DecodeEncodedWord($sEML)
ConsoleWrite(">>> $sSubject (_QuotedPrintable_DecodeEncodedWord): "&@CRLF&$sSubject&@CRLF)

$sSubject = StringReplace($sSubject, ChrW(55357) & ChrW(56520), "")  ; <---------------------------- ERROR?
ConsoleWrite(">>> $sSubject (StringReplace): "&@CRLF&$sSubject&@CRLF)



Global $aArray = StringSplit($sSubject, "", $STR_NOCOUNT)
For $i = 0 To UBound($aArray)-1
    ConsoleWrite($aArray[$i] & " - " & AscW($aArray[$i])& @CR)
Next

 

Share this post


Link to post
Share on other sites
18 minutes ago, Danp2 said:

This revised code works for me

For me as well.

To other interested users:
It is not necessary to integrate the source code of the "quoted-printable.au3" into your script. You can download the POP3.au3 UDF 2.0.1  by @mLipok . The Zip-file contains this .au3 - you can #include it , as usual.


Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By jmp
      I am adding labour charge to total paid amount using : 
      #include <IE.au3> #include <Array.au3> $oIE = _IEAttach ("Shop") $oTable = _IETableGetCollection ($oIE, 1) $aTableData3 = _IETableWriteToArray ($oTable) Local $sitem1 = $aTableData3[5][1] Local $sitem2 = $aTableData3[5][2] Local $lcharge = "10" ;add manualy using inputbox, becuase not generating online Local $atotPric = "Payable Total Price " Local $oTds = _IETagNameGetCollection($oIE, "td") For $oTd In $oTds If $oTd.Innertext = $atotPric Then $iatotPric = $oTd.NextElementSibling.innertext MsgBox (0, "2", $iatotPric) EndIf Next $irCtotal = StringFormat("%.2f", $sitem1 + $sitem2 + $lcharge) $crTotp = StringReplace(_IEBodyReadHTML($oIE), $iatotPric, $irCtotal) _IEBodyWriteHTML ($oIE, $crTotp) But, It was also changing Total price, I want to change only Payable Total Price.

    • By nooneclose
      Good morning everyone, I thought I had already solved this issue but it turns out I did not. 
      My code finds unread emails with this specific subject line of "request" but when I change the subject to SKIPPED + "request" = ("SKIPPED request") the program still finds the email and tries to process it. I only want to process emails with the exact match subject of "request".
      Here is my code that "finds" the unread emails with the subject of "request" or so I thought. 
      Func ListUnreadEmails() ;******************************************************************************* ; Lists all unread E-mails from the folder Outlook-UDF-Test ;******************************************************************************* ; Stores all the unRead emails into an array Global $aItems = _OL_ItemFind($oOutlook, "*\Outlook-UDF-Test", $olMail, _ "[UnRead]=True", "Subject", "request", "EntryID,Subject", "", 1) ; Displays the array of unRead emails If IsArray($aItems) Then ;_ArrayDisplay($aItems, "OutlookEX UDF: _OL_ItemFind - Unread mails") Else MsgBox(48, "OutlookEX UDF: _OL_ItemFind Example Script", _ "Could not find an unread mail. @error = " & @error & ", @extended: " & @extended) EndIf ; Gets the number of unread emails Global $numberOfUnRead = UBound($aItems, $UBOUND_ROWS) - 1 ;MsgBox("", "Number of Unread emails", $numberOfUnRead) EndFunc It acts as if any part of the subject containing the word "request" and the email is unread that it will try to process it. (I think)
    • By milos83
      Default keyword for optional parameter is interpreted wrongly.
      ConsoleWrite(StringReplace("aa", "a", "b", Default, 1) & @CRLF) StringReplace ( "string", "searchstring/start", "replacestring" [, occurrence = 0 [, casesense = 0]] ) The code above will output ab even thou the default value for the occurrence is 0 (replace all).
      Of course using zero instead of Default will work fine.
    • By smartkey
      Hi All,
           I have written a UDF for one of my requirement which replaces a single character in string with a sub string/another character. 
           I am using this for my requirement by calling below function as StrReplace("C:\Software\Autoit\Substr","\","\\") and gives result as C:\\Software\\Autoit\\Substr
           Please let me know if this can be improvised or any mistakes to correct.   
      ;===============================================================================
      ;
      ; Function Name:    StrReplace($INPUT_STRING)
      ; Description:      This function is to replace a character with another in a string.
      ; Parameter(s):     $INPUT_STRING     - Original String Value
      ;                    $STR_2_FIND     - Single Character to find the $INPUT_STRING
      ;                    $STR_2_REPLACE     - Substring/Multiple Characters to replace in place of     $STR_2_FIND value
      ; Requirement(s):   Replacing one single Character in a string with multiple Characters
      ; Return Value(s):  success - Output string after replacing a character with required character
      ;                    failure - 0
      ; Author(s):        smartkey
      ;
      ;===============================================================================
      Func StrReplace($INPUT_STRING, $STR_2_FIND, $STR_2_REPLACE)
          Local $OUTPUT_STRING = ""
          If StringLen($INPUT_STRING) > 0 Then
              If StringMid($INPUT_STRING,1,1) = $STR_2_FIND Then
                  $OUTPUT_STRING = $OUTPUT_STRING & $STR_2_REPLACE
              Else
                  $OUTPUT_STRING = StringMid($INPUT_STRING,1,1)
              EndIf
              For $i=2 to StringLen($INPUT_STRING)
                  If StringMid($INPUT_STRING,$i,1) = $STR_2_FIND Then
                      $OUTPUT_STRING= $OUTPUT_STRING & $STR_2_REPLACE
                  Else
                      $OUTPUT_STRING= $OUTPUT_STRING & StringMid($INPUT_STRING,$i,1)
                  EndIf
              Next
              Return $OUTPUT_STRING
          Else
              Return 0
          EndIf
      EndFunc
    • By Amixg
      Hi! I have another problem with AutoIT.  You see, I'm still the one who's just starting out with this great programming language. I have a problem with AutoIT, it seems not to recognize the "StringReplace" function even when it is by default. The code was made half in KODA and half of my own. It is a software programmed for the Italian language (I am Italian) and translate the SMS language into Italian correct. Would you help me? Thanks in advance.
       
      #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> $hull = "hello" StringReplace($hull, "hello", "hellx") $Form1 = GUICreate("Linguaggio SMS A Italiano", 507, 498, 192, 124) $Edit1 = GUICtrlCreateEdit("", 24, 40, 465, 177) GUICtrlSetData(-1, "") $Label1 = GUICtrlCreateLabel("Inserisci qui il testo che non riesci a capire:", 24, 8, 205, 17) $Label2 = GUICtrlCreateLabel("Ecco il testo tradotto(non toccare questo campo):", 27, 237, 237, 17) $Edit2 = GUICtrlCreateEdit("", 24, 264, 465, 137) GUICtrlSetData(-1, "") $Button1 = GUICtrlCreateButton("Traduci", 104, 424, 249, 49) GUISetState(@SW_SHOW) While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $Button1 StringReplace(GUICtrlGetData($Label1), "qlc", "qualcuno") StringReplace(GUICtrlGetData($Label1), "qls", "qualcosa") StringReplace(GUICtrlGetData($Label1), "ke", "che") StringReplace(GUICtrlGetData($Label1), "x", "per") StringReplace(GUICtrlGetData($Label1), "pls", "per favore") StringReplace(GUICtrlGetData($Label1), "tu6", "tu sei") StringReplace(GUICtrlGetData($Label1), "zzz", "mi fai dormire") StringReplace(GUICtrlGetData($Label1), "hagn", "Buonanotte") StringReplace(GUICtrlGetData($Label1), "tvtb", "Ti voglio tanto bene") StringReplace(GUICtrlGetData($Label1), "tat", "Ti amo tanto") StringReplace(GUICtrlGetData($Label1), "lafs", "Amore a prima vista") StringReplace(GUICtrlGetData($Label1), "fli?", "Flirtiamo?") StringReplace(GUICtrlGetData($Label1), "msidt", "Mi sono innamorato di te") StringReplace(GUICtrlGetData($Label1), "ba", "Bacio") StringReplace(GUICtrlGetData($Label1), "midi", "Mi dispiace.") StringReplace(GUICtrlGetData($Label1), "ntm", "Non ti merito") StringReplace(GUICtrlGetData($Label1), "tdp", "Togliti dai piedi.") StringReplace(GUICtrlGetData($Label1), "amò", "Amore") StringReplace(GUICtrlGetData($Label1), "ap", "A presto!") StringReplace(GUICtrlGetData($Label1), "cmq", "comunque") StringReplace(GUICtrlGetData($Label1), "cvd", "Ci vediamo dopo") StringReplace(GUICtrlGetData($Label1), "Tvb", "Ti voglio bene") StringReplace(GUICtrlGetData($Label1), "nn", "non") StringReplace(GUICtrlGetData($Label1), "risp", "rispondimi") StringReplace(GUICtrlGetData($Label1), "cel", "cellulare") StringReplace(GUICtrlGetData($Label1), "dom", "qualcosa") StringReplace(GUICtrlGetData($Label1), "nm", "numero") StringReplace(GUICtrlGetData($Label1), "fv", "favore") StringReplace(GUICtrlGetData($Label1), "-male", "meno male") StringReplace(GUICtrlGetData($Label1), "disc", "discoteca") StringReplace(GUICtrlGetData($Label1), "se#", "settimana") StringReplace(GUICtrlGetData($Label1), "+ o -", "più o meno") StringReplace(GUICtrlGetData($Label1), "ts", "torno subito") StringReplace(GUICtrlGetData($Label1), "tvtbcoa", "Ti voglio tanto bene come amica") EndSwitch WEnd  
×
×
  • Create New...