How to remove spaces and beginning 0 from a contact number in Views PHP view? I have tried multiple variations and I cannot get this right. I have a contact number field that is user input; therefore, I need to clean it up so that I can use it in a tel: link on mobile devices. 

Users could add numbers using different formats, such as:


021 457 7890
+27 21 567 7089
0214577898


What I want to do (using Views PHP) is to strip the spaces, +27, and 0 at the beginning. My PHP skills are limited, but the confusing part for me is the Value code input and the Output code input and getting this to output correctly.

Note: if there is a non-Views PHP workaround, that would be preferred.
You can do it using the PHP function str_replace 

$number = $row-&gt;field_contact_number;
// Remove the spaces.
$number = str_replace(' ', '', $number);
// Grab the first number. 
$first_number = substr($number, 0, 1); 
if ($first_number == 0) {
  // Check if the first number is 0.
  // Get rid of the first number.
  $number = substr($number, 1, 999); 
}
// Remove the + sign.
$number = str_replace('+', '', $number);
echo $number;




Although the question asked using Views PHP, it is not a good idea to enable the Views PHP and PHP Filter module. In Drupal 7, the alternative/preferred method would be to add the following code to the bottom of your template.php file (located in /sites/all/themes/yourtheme/ folder).

function themename_preprocess_views_view_fields($vars){
  if ($vars['view']-&gt;name == "view_name" &amp;&amp; $vars['view']-&gt;current_display == "block_1") {
    $number = $vars['fields']['field_contact_number']-&gt;content;
    // Remove the spaces.
    $number = str_replace(' ', '', $number);
    // Grab the first number. 
    $first_number = substr($number, 0, 1);
    if ($first_number == 0) {
      // Check if the first number is 0.
      // Get rid of the first number.
      $number = substr($number, 1, 999);
    }
    // Remove the + sign.
    $number = str_replace('+', '', $number);
    $vars['fields']['field_contact_number']-&gt;content = $number;
  }
}



Replace themename with your theme name
Replace view_name with your view name
Replace block_1 with your machine name


Remember to flush the cache to see the changes.