Hello, having a slight problem here..

I have a string, that I need to do character analysis on - Basically finding out how many times "B" is in the text and then ordering this from (lowest to highest). Now I can get the results, but, I don't know how to sort them. Any ideas?

<?php
		$string = "This is a test.";
		
		foreach (count_chars($string, 1) as $i => $val) {
		   echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
		}
		
?>

And the output would be something like:

String: T H I S I S A T E S T

Obviously not actual results but you know :)

Hope it's descriptive enough!

Member Avatar for diafol
$string = "This is a test.";
$s = count_chars($string, 1);
sort($s);
foreach ($s as $i => $val) {
   echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}

What's the output and the above got to do with each other? I don't understand that at all.

Ahh thank you for your reply, I've done it now (kind of)..

The problem is that, I'm reading from a text file and I want it to read the contents but ignoring all of the punctuation marks and spaces.. Here's the code:

$encrypted = "encrypted.txt";
$open = fopen($encrypted, 'r');
$string = fgets($open, 30);

echo $string; // prints "This is a test."

And I just need it to print "Thisisatest"

Any ideas? =)

Member Avatar for diafol

Any ideas? =)

Yes, but that's not the question you originally asked.

What do you want to leave - just letters, just letters and numbers, how about accented letters and multibyte characters (ï) etc?

OR

What do you want to strip? spaces, commas, semicolons, colons....

How about underscores and hyphens?

There are quite a few ways to use preg_replace() with this, we need to know exactly what to include or what to exclude.

This is quite a common question on programming tests... Is that coincidence? :)

Yes, but that's not the question you originally asked.

What do you want to leave - just letters, just letters and numbers, how about accented letters and multibyte characters (ï) etc?

OR

What do you want to strip? spaces, commas, semicolons, colons....

How about underscores and hyphens?

There are quite a few ways to use preg_replace() with this, we need to know exactly what to include or what to exclude.

The text just has whitespaces, commas and full stops.. I'll have a look at preg_replace :)

hmm... to replace all white space and special characters you could do something like this

//removes everything except letters
preg_replace( '~[^a-zA-Z]~', '', $str );

//removes white space only
str_replace(' ', '', $str);

//specfic characters like . and ! remember to escape it
preg_replace( '~[\.!]~', '', $str );

Finished :) Thank you for everyone who replied. I solved it by using preg_match() function

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.