ตัวอย่าง php replace space with underscore

Here’s an example of how to replace spaces with underscores in PHP:

PHP

<?php

// Sample string with spaces
$string = "This string has spaces";

// Method 1: Using str_replace() function
$replaced_string = str_replace(" ", "_", $string);

// Method 2: Using preg_replace() function (regular expression)
$replaced_string_regex = preg_replace('/\s+/', '_', $string);

// Display the original and replaced strings
echo "Original string: $string\n";
echo "Replaced string (str_replace): $replaced_string\n";
echo "Replaced string (preg_replace): $replaced_string_regex\n";

?>

Explanation:

  1. Original String: We define a variable $string containing the text with spaces.
  2. Method 1 (str_replace):
    • The str_replace function takes three arguments:
      • The character or string to replace (space in this case: ” “).
      • The replacement character or string (underscore: “_”).
      • The string to search within ($string).
    • It returns a new string with all occurrences of spaces replaced by underscores.
  3. Method 2 (preg_replace):
    • The preg_replace function uses a regular expression for more complex replacements.
      • The regular expression /\s+/ matches one or more whitespace characters (\s+).
    • It replaces all whitespace matches with underscores.
  4. Display: We echo the original string and both replaced versions.

Choosing the Method:

  • str_replace is simpler and sufficient for basic space replacements.
  • preg_replace offers more flexibility with regular expressions for advanced patterns.

This example demonstrates two ways to replace spaces with underscores in PHP. You can choose the method that best suits your needs.

Related Posts
 jquery vslidation remove spaces from input คืออะไร

jQuery validation remove spaces from input คือ ฟังก์ชันที่ใช้ลบช่องว่างออกจาก input field โดยใช้ jQuery วิธีใช้ JavaScri Read more

dimiss keyboard flutter คืออะไร

ใน Flutter dismiss keyboard หมายถึง การซ่อนแป้นพิมพ์เสมือนบนหน้าจอ วิธีการ dismiss keyboard ใช้ FocusNode: Dart imp Read more

bootstrap5 cdn คืออะไร

Bootstrap5 CDN คือ Content Delivery Network ของ Bootstrap 5 ซึ่งเป็นเฟรมเวิร์ก front-end ยอดนิยมที่ช่วยให้นักพัฒนาเว็บสร Read more

เขียนโค้ดดึงเนื้อหาจาก wordpress

โค้ดดึงเนื้อหาจาก WordPress วิธีดึงเนื้อหาจาก WordPress มีหลายวิธี ขึ้นอยู่กับประเภทของเนื้อหาที่ต้องการดึง ดึงบทความทั้ Read more