Skip to content

Commit 3c3ebaf

Browse files
committed
feat(string): improve trim() to handle Excel control characters
1 parent 217e02f commit 3c3ebaf

2 files changed

Lines changed: 12 additions & 2 deletions

File tree

src/Fluent/FluentString.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -437,13 +437,18 @@ public function uppercaseFirst(): self
437437
}
438438

439439
/**
440-
* Trim the string - supports unicode spaces
440+
* Trim the string - supports Unicode spaces and Excel control characters
441441
*
442442
* @return $this
443443
*/
444444
public function trim(): self
445445
{
446-
$this->value = preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $this->value);
446+
// 1) Remove Excel’s inline CR/LF escape tokens that appear as text
447+
// Handles case-insensitive _x000D_ and _x000A_
448+
$this->value = preg_replace('/^(_x000[da]_)+|(_x000[da]_)+$/i', '', $this->value);
449+
450+
// 2) Now trim real Unicode separators and control chars, including CR/LF
451+
$this->value = preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u', '', trim($this->value));
447452

448453
return $this;
449454
}

tests/Unit/Fluent/FluentStringTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,11 @@ public function testTrim(): void
357357
{
358358
$this->assertEquals('Test', str('Test')->trim());
359359
$this->assertEquals('Test', str("\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}Test\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}")->trim());
360+
361+
$this->assertEquals('Test', str('Test_x000d_')->trim());
362+
$this->assertEquals('Test', str('_x000d_Test')->trim());
363+
$this->assertEquals('Test', str('_x000d_Test_x000d_')->trim());
364+
$this->assertEquals('Test one _x000d_ two three', str('_x000d_Test one _x000d_ two three_x000d_')->trim());
360365
}
361366

362367
public function testIsEmailDomainValid(): void

0 commit comments

Comments
 (0)