KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Find position of the last occurrence of a substring in a string
PRODUCT: 4D | VERSION: 14.3 | PLATFORM: Mac & Win
Published On: December 12, 2014

Below is an utility method that uses the php function strrpos to find the position of the last occurrence of a substring in a string.

// Method: Php_strrpos
// Parameters
// $1 - Source string to find pattern
// $2 - pattern to search for
//
// Return
// $0 - position of the last occurrence of the pattern
// ----------------------------------------------------

C_TEXT($1;$2;$src;$pattern)
C_LONGINT($result;$0)

$src:=$1
$pattern:=$2

PHP Execute("";"strrpos";$result;$src;$pattern)

If($result#0)
  $0:=$result+1 //needed because in php, string positions start at 0, not 1
Else
  $0:=0 //pattern not found
End if


Below is an example of finding the last occurrence of a pattern in a string:
C_TEXT($src;$pattern)
C_LONGINT($pos)
$src:="test string test string"
$pattern:="test"
$pos:=Php_strrpos($src;$pattern)


$pos will return 13, which is the position of the last occurrence of the substring "test".

Commented by Vincent De Lachaux on December 15, 2014 at 7:04 AM
with regex:
ARRAY LONGINT($rxPositions;0)
ARRAY LONGINT($rxLengths;0)
$sourceText:="test string test string"
$rxPattern:="(?mi-s)(test)(?!.*test)"
$rxMatch:=Match regex($rxPattern;$sourceText;1;$rxPositions;$rxLengths)