Register (or login) on our website and you will not see this ad.
|
|
|
If I have the string $test="this is a test" and I execute the following:
$test = preg_replace("/this[ -]/", " ", $test);
It works fine but if I then try to force it to the beginning with:
$test = preg_replace("/$this[ -]/", " ", $test);
It does not work. Anyone know why and how to fix?
Thanks
|
|
|
Use ^ for the start of a string.
Sweet Thames, run softly till I end my song,
Sweet Thames, run softly, for I speak not loud or long.
|
|
|
Also, I'm not sure about the [ -]. What are you trying to match? With regex questions, it's always helpful to explain what you're trying to do and what the expected results are.
Sweet Thames, run softly till I end my song,
Sweet Thames, run softly, for I speak not loud or long.
|
|
Register (or login) on our website and you will not see this ad.
|
|
|
|
Sorry I am using a ^ I have gone through so many different combinations.
$test = preg_replace("/^this[ -]/", " ", $test);
It works fine on regular expression calculators but it does not work in PHP.
I want it to match "this" following by a space or hyphen at the start of the string. The string is always lowercase.
Thanks
|
|
|
What you've done should work. Here's my test script:
| Text | 1
23
45
67
89
1011
1213
1415
1617
1819
2021
2223
| <?php
$test = "this and that\n";echo preg_replace("/this[ -]/", " ", $test);
echo preg_replace("/^this[ -]/", " ", $test);echo preg_replace("/this[\ \-]/", " ", $test);
echo preg_replace("/^this[\ \-]/", " ", $test);
$test = "this-and-that\n";echo preg_replace("/this[ -]/", " ", $test);
echo preg_replace("/^this[ -]/", " ", $test);echo preg_replace("/this[\ \-]/", " ", $test);
echo preg_replace("/^this[\ \-]/", " ", $test);
Output is:
and that and that
and that and that
and-that and-that
and-that and-that |
I am using PHP 5.2.17 (old, I know) with Windows 7
Sweet Thames, run softly till I end my song,
Sweet Thames, run softly, for I speak not loud or long.
Edited by micksharpe (Fri 16-Jan-15 13:06:20)
|
|
|
|
Thanks this works fine.
Clearly I am doing something else that causes this not to work!
Back to trying to track it down.
|
|
|
Going back to your original description, might you have some white-space characters before the string you're searching for? When I'm debugging, I always print strings with delimiters, just to detect this sort of thing.
Sweet Thames, run softly till I end my song,
Sweet Thames, run softly, for I speak not loud or long.
|
|
|