Skip to content

Commit f844178

Browse files
committed
Added Str::words() method
1 parent 864c552 commit f844178

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

README.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,53 @@ $string->truncate(8); // Returns 'john...'
156156

157157
---
158158

159+
### words
160+
> Split the string into an array of words.
161+
162+
```php
163+
Twine\Str::words( void ) : array
164+
```
165+
166+
#### Examples
167+
168+
```php
169+
$string = new Twine\Str('john pinkerton');
170+
171+
$string->words(); // Returns ['john', 'pinkerton']
172+
```
173+
174+
```php
175+
$string = new Twine\Str('johnPinkerton');
176+
177+
$string->words(); // Returns ['john', 'Pinkerton']
178+
```
179+
180+
```php
181+
$string = new Twine\Str('JohnPinkerton');
182+
183+
$string->words(); // Returns ['John', 'Pinkerton']
184+
```
185+
186+
```php
187+
$string = new Twine\Str('john_pinkerton');
188+
189+
$string->words(); // Returns ['john', 'pinkerton']
190+
```
191+
192+
```php
193+
$string = new Twine\Str('john-pinkerton');
194+
195+
$string->words(); // Returns ['john', 'pinkerton']
196+
```
197+
198+
```php
199+
$string = new Twine\Str("john\npinkerton");
200+
201+
$string->words(); // Returns ['john', 'pinkerton']
202+
```
203+
204+
---
205+
159206
### append
160207
> Append one or more strings to the string.
161208

src/Traits/Segmentable.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,16 @@ public function truncate(int $length, string $suffix = '...') : self
5757
$this->first($length - strlen($suffix))->trimRight()->append($suffix)
5858
);
5959
}
60+
61+
/**
62+
* Split the string into an array of words.
63+
*
64+
* @return array An array of words.
65+
*/
66+
public function words() : array
67+
{
68+
preg_match_all('/[A-Z]?[a-z0-9]+/', $this->string, $matches);
69+
70+
return $matches[0];
71+
}
6072
}

tests/SegmentableTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,4 +101,13 @@ public function test_a_multiline_string_is_truncated_to_one_line_when_truncated_
101101

102102
$this->assertEquals('john pinkerton...', $truncated);
103103
}
104+
105+
public function test_it_can_be_split_into_an_array_of_words()
106+
{
107+
$string = new Twine\Str('john pinkerton-jingleHeimer_ShmidtJohnson');
108+
109+
$words = $string->words();
110+
111+
$this->assertEquals(['john', 'pinkerton', 'jingle', 'Heimer', 'Shmidt', 'Johnson'], $words);
112+
}
104113
}

0 commit comments

Comments
 (0)