البرمجة

تقسيم سلسلة PHP إلى جزئين

To split a string in PHP into two parts based on the last occurrence of a specific character (in this case, a dot), you can use the strrpos function to find the position of the last dot, and then use substr to extract the two parts of the string. Here’s how you can do it:

php
$ipadd = "192.168.1.60"; // Find the position of the last dot $lastDotPosition = strrpos($ipadd, '.'); // Split the string into two parts $part1 = substr($ipadd, 0, $lastDotPosition); $part2 = substr($ipadd, $lastDotPosition + 1); // Print the results echo "One is: $part1
"
; echo "Second is: $part2";

This code will output:

csharp
One is: 192.168.1 Second is: 60

This approach works by finding the position of the last dot using strrpos, and then using substr to extract the two parts of the string based on that position.

المزيد من المعلومات

بالطبع! في لغة PHP، يمكنك استخدام العديد من الدوال والتقنيات للتعامل مع النصوص وتقسيمها. إليك بعض المعلومات الإضافية التي قد تفيدك:

  1. استخدام الدالة explode: يمكنك استخدام الدالة explode لتقسيم سلسلة نصية إلى جزئين باستخدام النقطة كفاصل. ولكن هذه الطريقة ستقسم السلسلة إلى أكثر من جزء إذا كانت تحتوي على نقاط أخرى.

    php
    $ipadd = "192.168.1.60"; $parts = explode(".", $ipadd); $part1 = implode(".", array_slice($parts, 0, -1)); // Join all parts except the last one $part2 = end($parts); // Get the last part echo "One is: $part1
    "
    ; echo "Second is: $part2";
  2. استخدام الدالة substr وstrrchr: يمكنك استخدام الدالة strrchr للعثور على آخر حرف من نوع معين في السلسلة، ثم استخدام substr للحصول على الجزء الذي تريده.

    php
    $ipadd = "192.168.1.60"; $lastDotPosition = strrpos($ipadd, '.'); $part1 = substr($ipadd, 0, $lastDotPosition); $part2 = substr($ipadd, $lastDotPosition + 1); echo "One is: $part1
    "
    ; echo "Second is: $part2";
  3. استخدام الدالة preg_split: يمكنك استخدام الدالة preg_split لتقسيم السلسلة بناءً على تعبير منتظم، وفي هذه الحالة يمكننا استخدام التعبير الناتج عن دمج الرقم 1-9 والفاصلة، لذلك ستكون الدالة كما يلي:

    php
    $ipadd = "192.168.1.60"; $parts = preg_split("/[1-9]\./", $ipadd); $part1 = $parts[0]; $part2 = end($parts); echo "One is: $part1
    "
    ; echo "Second is: $part2";

تلك هي بعض الطرق التي يمكنك استخدامها في PHP لتقسيم السلاسل نصية إلى جزئين باستخدام النقطة كفاصل، واختيار الجزء الذي تريده بسهولة.

زر الذهاب إلى الأعلى