L
L
Like2beMike2021-11-25 22:26:43
PHP
Like2beMike, 2021-11-25 22:26:43

How to make a PHP regular expression to remove certain text?

I create a command to get the user's ID from a link on the page, there are three cases:
1. https://vk.com/none
2. https://vk.com/id123
3. @none
In the first case, the regular expression should leave only none.
In the second, everything is the same as in the first, cut to id123.
In the third case, nothing should be deleted.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stalker_RED, 2021-11-26
@Like2beMike

Replacing via str_replace is enough

$newStr = str_replace('https://vk.com/', '', $str);

V
Vladislav, 2021-11-25
@cr1gger

<?php
$a = 'https://vk.com/none';
$b = 'https://vk.com/id123';
$c = 'https://vk.com/id123456?a=b';
$d = '@none';
$e = 'some text';

function getUserId($link)
{
    if (preg_match('/vk.com\/(?<id>[\w\d]+)/ui', $link, $m) && !empty($m['id'])) return $m['id'];
    if (preg_match('/(?<uid>@[\w\d]+)/ui', $link, $m) && !empty($m['uid'])) return $m['uid'];
    return false;
}

var_dump(getUserId($a));
var_dump(getUserId($b));
var_dump(getUserId($c));
var_dump(getUserId($d));
var_dump(getUserId($e));

//string(4) "none"
//string(5) "id123"
//string(8) "id123456"
//string(5) "@none"
//bool(false)

A
alexanderzanin, 2021-11-25
@alexanderzanin

$string = 'https://vk.com/none';

function find(string $str) {
    $result = '';
    if (preg_match('/^https:\/\/vk.com\//', $str)) {
        $result = substr($str, 15);
    } else {
        $result = $str;
    }

    return $result;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question