سؤال

Ok so I am taking a string, querying a database and then must provide a URL back to the page. There are multiple special characters in the input and I am stripping all special characters and spaces out using the following code and replacing with HTML "%25" so that my legacy system correctly searches for the value needed. What I need to do however is cut down the number of "%25" that show up.

My current code would replace something like

"Hello. / there Wilbur" with "Hello%25%25%25%25there%25Wilbur"

but I would like it to return

"Hello%25there%25Wilbur"

replacing multiples of the "%25" with only one instance

$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9]/', '%25', $string); // Replaces special chars.
هل كانت مفيدة؟

المحلول

Just add a + after selecting a non-alphanumeric character.

$string = "Hello. / there Wilbur";
$string = str_replace(' ', '-', $string);

// Just add a '+'. It will remove one or more consecutive instances of illegal
// characters with '%25'
return preg_replace('/[^A-Za-z0-9]+/', '%25', $string);

Sample input: Hello. / there Wilbur

Sample output: Hello%25there%25Wilbur

نصائح أخرى

This will work:

while (strpos('%25%25', $str) !== false)
    $str = str_replace('%25%25', '%25', $str);

Or using a regexp:

preg_replace('#((?:\%25){2,})#', '%25', $string_to_replace_in)

No looping using a while, so the more consecutive '%25', the faster preg_replace is against a while.

Cf PHP doc:

http://fr2.php.net/manual/en/function.preg-replace.php

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top