0
I’m following the playbook OOP Programming with PHP5 by Hasin Hayder (2007) and arrived at the part of Unit Tests. In given exercise, he sets up a method wordCount()
and creates some tests for this method,
class WordCount
{
public function countWords($sentence)
{
return count(split(" ",$sentence));
}
}
which returns all the words of the variable, ie: $this->assertEquals(4, $wordcount);
, if the variable is something like: "my name is john"
he will have four words.
It creates a test in case the variable has more spaces: "my name is john "
(notice the space after John), that when we wheel returns Failure
.
To solve, it modifies the method and adds the preg_replace
and that regex there "~\s+~"
and its code works as expected, but, I used the same thing and it didn’t work.
It even creates another test, where the variable is "my name is \n\r john"
and the same regex realized.
class WordCount
{
public function countWords($sentence)
{
$newsentence = preg_replace("~\s+~"," ",$sentence);
return count(split(" ",$newsentence));
}
}
I have checked my code to find possible syntax or structure errors, but everything is ok, at least, the same as what it says in the exercise.
To solve the first two tests, I found preg_replace('/\s*$/','',$sentence);
which worked, but the test where there is the \n\r
did not pass.
So I’d like to know:
- Why the regex he used didn’t work?
- How would a regex remove extra spaces and Carriage Return/new line (
\n\r
);
The complete codes used are here:
What is the connection of the question with phpunit and unit testing? If the question is not directly related to them, it is best to [Edit] and remove these tags
– gmsantos
But has it sent some error message with the word "deprecated"? Because something not working does not mean it is in disuse. Tomorrow I try to understand the problem.
– Guilherme Nascimento
gmsantos, already removed. William, no error appeared with "deprecated", the test just did not pass in phpunit. In the tutorial, passes, but when I did, did not give
– wdarking
If nothing appears from "deprecated" why the question title cites that?
– gmsantos
because it is the doubt that I have. the regex "~ s+~" was belittled? because I believe phpunit would not show errors related to this, so I suppose this regex format is old/deprecated.
– wdarking
regex is ok for PHP. I just tested your code, the problem is another, I’m responding.
– gmsantos
@gmsantos is already responding, I was going to say
split
is disused see: http://php.net/manual/en/function.split.php– Guilherme Nascimento
Recommendation : http://answall.com/questions/110701/o-que-significa-o-shortcut-s-nas-regex
– Guilherme Lautert