Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    Regular Coder
    Join Date
    Feb 2011
    Posts
    114
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Help me on preg_replace i'm working on

    Hi,
    Please i'm writing a program using a regular expression .
    Now , i created a string called 'this is a test' and i want to replace 'test' with 'assignment', i try this code but not working , can someone help me
    Here is the code


    Code:
    [<?php] 
       $string='this is a test';
      $preg_replace= preg_replace('/[a-zA-Z]/','assignment', $string);
       echo $preg_replace;
       
    [ ?>]
    Thanks
    Clement Osei

  • #2
    Senior Coder djm0219's Avatar
    Join Date
    Aug 2003
    Location
    Wake Forest, North Carolina
    Posts
    1,306
    Thanks
    4
    Thanked 205 Times in 202 Posts
    No reason to use preg_replace for a simple replacement like that.

    PHP Code:
    $string='this is a test';
    echo 
    str_replace('test','assignment',$string); 
    Dave .... HostMonster for all of your hosting needs

  • #3
    Regular Coder
    Join Date
    Feb 2011
    Posts
    114
    Thanks
    12
    Thanked 0 Times in 0 Posts
    Hi Sir,,
    Thanks very much for your reply.
    Well , i do know how to use the str_replace but want to know using preg_replace.

    Please can you help me out ,using the example above.

    Thanks Much.

    Clement Osei

  • #4
    Senior Coder
    Join Date
    Jul 2011
    Posts
    1,226
    Thanks
    3
    Thanked 171 Times in 171 Posts
    For simple ones like your example, str_replace is a LOT faster (processing wise).

    Regular expressions should only be used to match patterns - something you don't know specifically the value of, or a pattern you need to replace (like parsing BB code).

    In other words, learn how to use it with its proper designed application.
    Useful function to retrieve difference in times
    The best PHP resource
    A good PHP FAQ
    PLEASE remember to wrap your code in [PHP] tags.
    PHP Code:
    // Replace this
    if(isset($_POST['submitButton']))
    // With this
    if(!empty($_POST))
    // Then check for values/forms. Some IE versions don't send the submit button 
    Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.

  • #5
    Regular Coder
    Join Date
    Feb 2011
    Posts
    114
    Thanks
    12
    Thanked 0 Times in 0 Posts
    Hi Sir,
    Thanks for your advise.
    I really appreciate it..!!

    Clement Ose1


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •